package com.zhangtai.modules.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.Neusoft.service.NeusoftSecurityService;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.modules.constVo.SecurityConst;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.*;
import com.zhangtai.modules.dto.*;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.employee.EmployeeSecurityEntity;
import com.zhangtai.modules.entity.employee.EmployerCompanyEntity;
import com.zhangtai.modules.entity.security.*;
import com.zhangtai.modules.entity.system.ContractSubGroupEntity;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.service.employee.EmployeeSecurityService;
import com.zhangtai.modules.service.security.*;
import com.zhangtai.modules.vo.*;
import com.zhangtai.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;

import static com.zhangtai.modules.constVo.SecurityConst.*;

@RestController
@Slf4j
@RequestMapping("security")
@Api(tags = "社保公积金接口")
public class SecurityController {

    @Autowired
    private SecurityService securityService;

    @Autowired
    private SecurityItemDao securityItemDao;
    @Autowired
    private SecurityItemService securityItemService;
    @Autowired
    private SecurityChangeService securityChangeService;
    @Autowired
    private LoginController loginController;
    @Autowired
    private SecurityRecordService securityRecordService;
    @Autowired
    private EmployeeSecurityDao employeeSecurityDao;
    @Autowired
    private JobController jobController;
    @Autowired
    private EmployeeSecurityService employeeSecurityService;
    @Autowired
    private FundsRecordService fundsRecordService;
    @Autowired
    private EmployeeInfoService employeeInfoService;
    @Autowired
    private SecurityChangeDao securityChangeDao;
    @Autowired
    private SecurityBatchGroupService securityBatchGroupService;
    @Autowired
    private SecurityBatchService securityBatchService;
    @Autowired
    private SecurityBatchGroupDao securityBatchGroupDao;
    @Autowired
    private EmployerCompanyDao employerCompanyDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private NeusoftSecurityService neusoftSecurityService;
    @Autowired
    private SecurityDao securityDao;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private SecurityRecordDao securityRecordDao;
    @Autowired
    private FundsRecordDao fundsRecordDao;

//


//    @PostMapping("/getSecurityList")
//    @ApiOperation("社保公积金方案列表")
//    @PreAuthorize("hasAuthority('emp:security:update')")
//    public R< PageResult<SecurityDto>> getSecurityList(@RequestBody() @Valid SecurityListVo securityListVo){
//        String date = DateUtils.format(new Date(),"yyyy-MM");
//      PageResult<SecurityDto> result = securityService.getSecurityList(securityListVo.getPageNum(),securityListVo.getPageSize(),securityListVo.getSecurityName(),
//                securityListVo.getUnitName(),securityListVo.getCityName(),securityListVo.getStatus(),securityListVo.getNumber(),securityListVo.getType(),date+"-01 00:00:00",date+"-31 23:59:59");
//
//      return R.ok(result);
//    }

    // 带权限社保公积金方案查询
    @PostMapping("/getSecurityList")
    @ApiOperation("社保公积金方案列表")
    @PreAuthorize("hasAuthority('emp:security:update')")
    public R<PageResult<SecurityDto>> getSecurityList(@RequestBody() @Valid SecurityListVo securityListVo, HttpServletRequest request) throws Exception {
        //验证是否有用户权限
        //获取当前用户角色下合同主体Id
        R checkR = loginController.checkContractPermission(request);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<ContractSubGroupEntity> contractSubs = (List<ContractSubGroupEntity>) checkR.getData();
        ArrayList<Long> contractIds = new ArrayList<Long>();
        for (ContractSubGroupEntity item : contractSubs
        ) {
            contractIds.add(item.getId());
        }

        String date = DateUtils.format(new Date(), "yyyy-MM");
        PageResult<SecurityDto> result = securityService.getSecurityList(securityListVo.getPageNum(), contractIds, securityListVo.getPageSize(), securityListVo.getSecurityName(),
                securityListVo.getUnitName(), securityListVo.getCityName(), securityListVo.getStatus(), securityListVo.getNumber(), securityListVo.getType(), date + "-01 00:00:00", date + "-31 23:59:59");

        return R.ok(result);
    }


    //
    @PostMapping("/getFundsRecordList")
    @ApiOperation("公积金缴费记录")
    @PreAuthorize("hasAuthority('emp:socialSecurity:update')")
    public R<PageResult<FundsRecordDto>> getFundsRecordList(@RequestBody @Valid SecurityRecordVo securityRecordVo, HttpServletRequest request) throws Exception {
        String time = "";
        String endTime = "";
        //获取当前用户角色下公司Id
//        R checkR = loginController.checkOrgPermission(request,null,false);
//        if(!R.isOk.equals(checkR.getStatus())){
//            return checkR;
//        }
//        List<Long> orgIds = (List<Long>) checkR.getData();

        R checkC = loginController.checkContractPermission(request);
        if (!R.isOk.equals(checkC.getStatus())) {
            return checkC;
        }
        List<ContractSubGroupEntity> contractSubs = (List<ContractSubGroupEntity>) checkC.getData();
        ArrayList<Long> contractIds = new ArrayList<Long>();
        for (ContractSubGroupEntity item : contractSubs
        ) {
            contractIds.add(item.getId());
        }

        if (!ObjectUtils.isEmpty(securityRecordVo.getOperateTime())) {
            time = DateUtils.format(securityRecordVo.getOperateTime(), "yyyy-MM") + "-01 00:00:00";
            endTime = DateUtils.format(securityRecordVo.getOperateTime(), "yyyy-MM") + "-31 23:59:59";
        }else{
            time = DateUtils.getBeginDayOfMonth() + " 00:00:00";
            endTime = DateUtils.getLastDayOfMonth() + " 23:59:59";
        }
        PageResult<FundsRecordDto> recordMap = fundsRecordService.getRecordListAuth(time, endTime, securityRecordVo.getIsCheck(),
                securityRecordVo.getIsConfirm(), securityRecordVo.getType(),
                securityRecordVo.getUnitName(), securityRecordVo.getCityName(), null,
                securityRecordVo.getName(), null, contractIds, securityRecordVo.getUnitId(),
                securityRecordVo.getPageNum(), securityRecordVo.getPageSize());

        return R.ok(recordMap);
    }


//
//    @PostMapping("/getFundsRecordList")
//    @ApiOperation("公积金缴费记录")
//    @PreAuthorize("hasAuthority('emp:socialSecurity:update')")
//    public R<PageResult<FundsRecordDto>> getFundsRecordList(@RequestBody @Valid SecurityRecordVo securityRecordVo,HttpServletRequest request)throws Exception{
//        String time = "";
//        String endTime = "";
//        //获取当前用户角色下公司Id
//        R checkR = loginController.checkOrgPermission(request,null,false);
//        if(!R.isOk.equals(checkR.getStatus())){
//            return checkR;
//        }
//        List<Long> orgIds = (List<Long>) checkR.getData();
//
//        R checkC = loginController.checkContractPermission(request);
//        if(!R.isOk.equals(checkC.getStatus())){
//            return checkC;
//        }
//        List<ContractSubGroupEntity> contractSubs = (List<ContractSubGroupEntity>) checkC.getData();
//        ArrayList<Long> contractIds = new ArrayList<Long>();
//        for (ContractSubGroupEntity item:contractSubs
//                ) {
//            contractIds.add(item.getId());
//        }
//
//        if(!ObjectUtils.isEmpty(securityRecordVo.getOperateTime())){
//            time = DateUtils.format(securityRecordVo.getOperateTime(),"yyyy-MM")+"-01 00:00:00";
//            endTime = DateUtils.format(securityRecordVo.getOperateTime(),"yyyy-MM")+"-31 23:59:59";
//        }
//        PageResult<FundsRecordDto> recordMap = fundsRecordService.getRecordListAuth(time,endTime,securityRecordVo.getIsCheck(),
//                securityRecordVo.getIsConfirm(),securityRecordVo.getType(),
//                securityRecordVo.getUnitName(),securityRecordVo.getCityName(),null,
//                securityRecordVo.getName(),orgIds,contractIds,
//                securityRecordVo.getPageNum(),securityRecordVo.getPageSize());
//
//        return  R.ok(recordMap);
//    }


    @GetMapping("/getAllSecurityList")
    @ApiOperation("获取所有方案")
    @PreAuthorize("hasAuthority('emp:socialSecurity:get')")
    public R<List<SecurityEntity>> getAllSecurityList(@RequestParam(value = "type") Integer type) {
        List<SecurityEntity> list = securityService.getAllSecurityList(type);
        return R.ok(list);
    }


//    @PostMapping("/deleteSecurity")
//    @ApiOperation("删除社保方案")
//    @SysAuthorityLog(value = "删除社保方案")
//    @PreAuthorize("hasAuthority('emp:security:delete')")
//    @Transactional
//    public R deleteSecurity(Integer type,String typeId){
//        //删除个人对应社保方案信息
//        if(SecurityConst.ITEM_TYPE_ENDOWMENT.equals(type)){
//            securityRecordService.deleteAllRecordBySecurityId(Long.parseLong(typeId));
//            employeeSecurityDao.deleteSecurity(Long.parseLong(typeId));
//
//        }else{
//            fundsRecordService.deleteAllRecordBySecurityId(Long.parseLong(typeId));
//            employeeSecurityDao.deleteFunds(Long.parseLong(typeId));
//        }
//        //删除社保方案信息
//        securityService.removeOneById(Long.parseLong(typeId));
//
//        return R.ok();
//    }

    @PostMapping("/deleteSecurity")
    @ApiOperation("删除社保方案")
    @SysAuthorityLog(value = "删除社保方案")
    @PreAuthorize("hasAuthority('emp:security:delete')")
    @Transactional
    public R deleteSecurity(Integer type, String typeId, HttpServletRequest request) throws Exception {
        //删除个人对应社保方案信息
        if (SecurityConst.ITEM_TYPE_ENDOWMENT.equals(type)) {
            securityRecordService.deleteAllRecordBySecurityId(Long.parseLong(typeId));
            employeeSecurityDao.deleteSecurity(Long.parseLong(typeId));

        } else {
            fundsRecordService.deleteAllRecordBySecurityId(Long.parseLong(typeId));
            employeeSecurityDao.deleteFunds(Long.parseLong(typeId));
        }
        //删除社保方案信息
        securityService.removeOneById(Long.parseLong(typeId));
        //更新redis中的缓存
        //根据社保id查公司名字 查主体id
//        SecurityEntity byIdE = securityService.getByIdE(new Long(typeId));
//
//        EmployerCompanyEntity employerCompanyEntity = employerCompanyDao
//                .selectOne(new QueryWrapper<EmployerCompanyEntity>().eq("name", byIdE.getUnitName()) );
//
//        //存到redis
//        R uR = loginController.getUserInfo(request);
//        JSONObject user = (JSONObject) uR.getData();
//        String userId = user.getString("userId");
//
//        List<String> mainIds = (List<String>) redisTemplate.boundValueOps("contractPermission" + userId).get();
//        mainIds.remove(employerCompanyEntity.getId().toString());
//        redisTemplate.boundValueOps("contractPermission" + userId).set(mainIds);

        return R.ok();
    }


    @PostMapping("/saveOrUpdateSecurity")
    @ApiOperation("插入/更新社保公积金主体信息")
    @SysAuthorityLog(value = "更新社保公积金主体信息")
    @Transactional
    @PreAuthorize("hasAuthority('emp:security:update')")
    public R saveOrUpdateSecurity(@RequestBody @Valid SecurityVo securityVo, HttpServletRequest request) throws Exception {
        SecurityEntity securityEntity = BeanUtilsMabach.doToDto(securityVo, SecurityEntity.class);
        //新增/更新 存到redis 主体id 存到 contractMainId
        //存到redis
        //根据公司名字查主体id
        EmployerCompanyEntity employerCompanyEntity = employerCompanyDao
                .selectOne(new QueryWrapper<EmployerCompanyEntity>().eq("name", securityEntity.getUnitName()).eq("is_delete", 0));
        if (ObjectUtils.isEmpty(employerCompanyEntity)) {
            return R.error("缴纳单位不存在!");
        }

        securityEntity.setContractMainId(employerCompanyEntity.getId());
        if (ObjectUtils.isEmpty(securityEntity.getSecurityId())) {
            SecurityEntity entity = securityService.getByUnitName(securityEntity.getUnitName(), securityVo.getType());
            if (!ObjectUtils.isEmpty(entity)) {
                return R.error("该缴纳单位已绑定方案，无法新增！");
            }
            securityService.saveE(securityEntity);
            securityVo.setSecurityId(securityEntity.getSecurityId());
        } else {
            securityService.updateByIdE(securityEntity);
        }
        //存到redis
        R uR = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) uR.getData();
        String userId = user.getString("id");

        List<Long> contractGoupIds = (List<Long>) redisTemplate.boundValueOps("contractPermission" + userId).get();

        List<ContractSubGroupEntity> contractMainIds = null;
//        if(!com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(contractGoupIds)) {
//            contractMainIds = contractSubGroupDao.getContractMainIds(contractGoupIds);
//        }
//
//        if(employerCompanyEntity.getId()!=null) {
//        if(!CollectionUtils.isEmpty(contractMainIds)) {
//                if(contractMainIds.contains(employerCompanyEntity.getId().toString())){
//
//                }else{
//                    contractMainIds.add(employerCompanyEntity.getId().toString());
//                }
//        }else {
//            contractMainIds = new ArrayList<String>();
//        }
//
//            securityEntity.setContractMainId(employerCompanyEntity.getId());
//        }
     /*   Long securityId = securityEntity.getSecurityId();
        jobController.sMap.put(securityId,securityEntity);*/
        SecurityItemVo securityItemVo = new SecurityItemVo();
        securityItemVo.setSecurityId(securityEntity.getSecurityId());
        securityItemVo.setSecurityItemVoList(securityVo.getSecurityItem());
        R itemR = saveOrUpdateSecurityItem(securityItemVo);
        String userCode = user.getString("usercode");
        String name = user.getString("name");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    updateSecurityRecord(securityVo, request, name, userCode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return itemR;
    }

    @PostMapping("/getItemBySecurityId")
    @ApiOperation("获取社保公积金方案细类")
    @PreAuthorize("hasAuthority('emp:securityEmp:update')")
    public R<List<SecurityItemEntity>> getItemBySecurityId(@RequestParam(value = "securityId") String securityId) {
        List<SecurityItemEntity> list = securityItemService.getItemBySecurityId(Long.parseLong(securityId));
        return R.ok(list);
    }

    @GetMapping("/getUserSecurityDetail")
    @ApiOperation("获取员工社保公积金详情")
    @PreAuthorize("hasAuthority('emp:socialSecurity:get')")
    public R getUserSecurityDetail(String oid) {
        EmployeeSecurityEntity employeeSecurityEntity = employeeSecurityService.getByIdE(Long.parseLong(oid));
        return R.ok(employeeSecurityEntity);
    }


    /**
     * 插入/更新社保公积金细类
     *
     * @param securityItemVo
     * @return
     */
    public R saveOrUpdateSecurityItem(SecurityItemVo securityItemVo) {
        List<Integer> type = new ArrayList<>();
        for (SecurityItemEntity item : securityItemVo.getSecurityItemVoList()) {
            if (type.contains(item.getSecurityType())) {
                return R.error(SecurityConst.typeName.get(item.getSecurityType()) + "已存在！");
            }
            type.add(item.getSecurityType());
        }
        Long securityId = securityItemVo.getSecurityId();
        securityItemDao.delete(new QueryWrapper<SecurityItemEntity>()
                .eq(!ObjectUtils.isEmpty(securityId), "security_id", securityId));
        Map<Integer, SecurityItemEntity> itemMap = new HashMap<>();
        for (SecurityItemEntity item : securityItemVo.getSecurityItemVoList()) {
            item.setSecurityId(securityId);
            securityItemDao.insert(item);
            itemMap.put(item.getSecurityType(), item);
            type.add(item.getSecurityType());
        }
        //jobController.securityMap.put(securityId, itemMap);
        return R.ok();
    }

    @DeleteMapping("/deleteSecurityItem")
    @ApiOperation("删除社保公积金子项信息")
    @SysAuthorityLog(value = "删除社保公积金子项信息")
    @Transactional
    @PreAuthorize("hasAuthority('emp:security:delete')")
    public R deleteSecurityItem(@RequestParam(value = "itemId") String itemId) {
        securityItemService.removeOneById(Long.parseLong(itemId));
        return R.ok();
    }

    @PostMapping("/changeSecurity")
    @ApiOperation("保存社保公积金子增员/减员记录")
    @SysAuthorityLog(value = "保存社保公积金子增员/减员记录")
    @Transactional
    @PreAuthorize("hasAuthority('emp:socialSecurity:update')")
    public R changeSecurity(@RequestBody @Valid SecurityChangeVo securityChangeVo, HttpServletRequest request, String n, String code) throws Exception {
        SecurityChangeEntity changeEntity = BeanUtilsMabach.doToDto(securityChangeVo, SecurityChangeEntity.class);
        SecurityEntity securityEntity = securityService.getByIdE(securityChangeVo.getSecurityId());
        changeEntity.setOperationTime(new Date());
        changeEntity.setOid(securityChangeVo.getOid());
        changeEntity.setType(securityChangeVo.getType());
        R uR = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) uR.getData();
        String userCode = code;
        String name = n;
        if (!ObjectUtils.isEmpty(user)) {
            userCode = user.getString("usercode");
            name = user.getString("name");
        }
        changeEntity.setOperaterCode(userCode);
        changeEntity.setOperateName(name);
        SecurityRecordEntity securityRecordEntity = new SecurityRecordEntity();
        String errorMsg = "";
        Date date;
        //缴纳月份
        if (!ObjectUtils.isEmpty(securityChangeVo.getOperateTime())) {
            date = securityChangeVo.getOperateTime();
        } else {
            date = new Date();
        }
        securityRecordEntity.setOperateTime(date);
        securityRecordEntity.setCreateTime(new Date());
        //变更类型是增员/补缴/更新，加入缴费记录
        if (SecurityConst.CHANGE_TYPE_ADD.equals(changeEntity.getType()) ||
                SecurityConst.CHANGE_TYPE_CHANGE.equals(changeEntity.getType()) ||
                SecurityConst.CHANGE_TYPE_UPDATE.equals(changeEntity.getType())) {
            String startDay = DateUtils.format(securityRecordEntity.getOperateTime(), "yyyy-MM") + "-01 00:00:00";
            String endDay = DateUtils.format(securityRecordEntity.getOperateTime(), "yyyy-MM") + "-31 23:59:59";
            changeEntity.setSecurityId(securityChangeVo.getSecurityId());
            //添加公积金缴费记录
            if (SecurityConst.SECURITY_TYPE_FUNDS.equals(securityEntity.getType())) {
                FundsRecordEntity fundsRecordEntity = new FundsRecordEntity();
                fundsRecordEntity.setCreateTime(date);
                fundsRecordEntity.setUnitName(securityEntity.getUnitName());
                fundsRecordEntity.setCityName(securityEntity.getCityName());
                fundsRecordEntity.setOid(securityChangeVo.getOid());
                fundsRecordEntity.setSecurityId(securityEntity.getSecurityId());
                //查询当月是否有未处理的缴费记录
                FundsRecordEntity oldRecord = fundsRecordService.getByOidAndType(securityChangeVo.getOid(), 1, startDay, endDay);
                if (ObjectUtils.isEmpty(oldRecord)) {
                    addFundsRecord(securityChangeVo.getOid(), userCode, name, fundsRecordEntity, securityChangeVo.getOperateTime(), SecurityConst.CHANGE_TYPE_ADD);
                } else {
                    errorMsg = "当月已有确认过的缴费记录，无法补缴!";
                }

            } else {
//
                securityRecordEntity.setUnitName(securityEntity.getUnitName());
                securityRecordEntity.setCityName(securityEntity.getCityName());
                securityRecordEntity.setOid(securityChangeVo.getOid());
                securityRecordEntity.setSecurityId(securityEntity.getSecurityId());
                //查询当月是否有未处理的缴费记录
                SecurityRecordEntity oldRecord = securityRecordService.getByOidAndType(securityChangeVo.getOid(), 1, startDay, endDay);
                if (ObjectUtils.isEmpty(oldRecord)) {
                    addSecurityRecord(securityChangeVo.getOid(), userCode, name, securityRecordEntity, securityChangeVo.getOperateTime(), SecurityConst.CHANGE_TYPE_ADD);
                } else {
                    errorMsg = "当月已有确认过的缴费记录，无法补缴!";
                }
            }
        }
        //变更类型是减员，删除缴费记录
        else if (SecurityConst.CHANGE_TYPE_REDUCE.equals(changeEntity.getType())) {
//            addSecurityRecord(securityChangeVo.getOid(), userCode, name, securityRecordEntity,SecurityConst.CHANGE_TYPE_REDUCE);
            changeEntity.setSecurityId(null);
            changeEntity.setSecurityId(securityChangeVo.getSecurityId());
            securityRecordEntity.setOid(securityChangeVo.getOid());
            String startDay = DateUtils.getBeginDayOfMonth();
            String endDay = DateUtils.getLastDayOfMonth();
            //删除本月公积金未处理的缴费记录
            if (SecurityConst.SECURITY_TYPE_FUNDS.equals(securityEntity.getType())) {
                fundsRecordService.removeUnCheckEntity(securityRecordEntity.getOid(), startDay, endDay);
            } else {
                securityRecordService.removeUnCheckEntity(securityRecordEntity.getOid(), startDay, endDay);
            }

        }
        securityChangeService.saveE(changeEntity);
        if (StringUtils.isEmpty(errorMsg)) {
            return R.ok();
        } else {
            return R.error(errorMsg);
        }
    }

    /**
     * 添加公积金缴费记录
     *
     * @param oid
     * @param userCode
     * @param name
     * @param fundsRecordEntity
     * @param operateTime       缴费月份
     * @param type
     */
    public void addFundsRecord(Long oid, String userCode, String name, FundsRecordEntity fundsRecordEntity, Date operateTime, Integer type) {
        String startDay = DateUtils.format(operateTime, "yyyy-MM") + "-01 00:00:00";
        String endDay = DateUtils.format(operateTime, "yyyy-MM") + "-31 23:59:59";
        EmployeeSecurityEntity employeeSecurityEntity = employeeSecurityDao.selectOne(new QueryWrapper<EmployeeSecurityEntity>().eq("oid", oid));
        //获取方案对应公积金信息
        Map<Integer, SecurityItemEntity> fundsMap = jobController.securityMap.get(employeeSecurityEntity.getFundsId());
        FundsRecordEntity oldRecord = fundsRecordService.getByOidAndType(oid, 0, startDay, endDay);
        //存在未处理的缴费记录，设置对应recordId更新记录
        if (!ObjectUtils.isEmpty(oldRecord)) {
            fundsRecordEntity.setRecordId(oldRecord.getRecordId());
        }
        BigDecimal personCostTotal = new BigDecimal(0);
        BigDecimal orgCostTotal = new BigDecimal(0);
        SecurityItemEntity fundsItem = fundsMap.get(SecurityConst.ITEM_TYPE_FUNDS);//公积金
        SecurityItemEntity offerFundsItem = fundsMap.get(SecurityConst.ITEM_TYPE_OFFER_FUNDS);//补充公积金
        SecurityItemDto funds = handleSecurityItem(fundsItem, SecurityConst.ITEM_TYPE_ENDOWMENT, employeeSecurityEntity.getReservedFunds());
        SecurityItemDto offerFunds = handleSecurityItem(offerFundsItem, SecurityConst.ITEM_TYPE_ENDOWMENT, employeeSecurityEntity.getOfferFunds());
        //公积金
        fundsRecordEntity.setReservedFundsOrg(funds.getOrgCost());
        fundsRecordEntity.setReservedFundsOrgRate(funds.getOrgRate());
        fundsRecordEntity.setReservedFundsPerson(funds.getPersonCost());
        fundsRecordEntity.setReservedFundsPersonRate(funds.getPersonRate());
        fundsRecordEntity.setReservedFundsBase(funds.getBase());

        //补充公积金
        fundsRecordEntity.setOfferFundsOrg(offerFunds.getOrgCost());
        fundsRecordEntity.setOfferFundsOrgRate(offerFunds.getOrgRate());
        fundsRecordEntity.setOfferFundsPerson(offerFunds.getPersonCost());
        fundsRecordEntity.setOfferFundsPersonRate(offerFunds.getPersonRate());
        fundsRecordEntity.setOfferFundsBase(offerFunds.getBase());
        //个人缴费合计
        personCostTotal = funds.getPersonCost().add(offerFunds.getPersonCost());
        fundsRecordEntity.setPersonCostTotal(personCostTotal);
        //公司缴费合计
        orgCostTotal = funds.getOrgCost().add(offerFunds.getOrgCost());
        fundsRecordEntity.setOrgCostTotal(orgCostTotal);
        fundsRecordEntity.setSalaryCost(personCostTotal);
        fundsRecordEntity.setOperateName(name);
        fundsRecordEntity.setOperateCode(userCode);
        fundsRecordEntity.setOperateTime(operateTime);
        fundsRecordEntity.setType(type);
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(oid);
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            return;
        }
//        fundsRecordEntity.setOrgId(employeeInfoEntity.getOrgId());
        fundsRecordEntity.setUnitId(employeeInfoEntity.getUnitId());
        saveOrUpdateFundsRecord(fundsRecordEntity);
    }

    /**
     * 添加社保缴费记录
     *
     * @param oid
     * @param userCode
     * @param name
     * @param securityRecordEntity
     * @param operateTime          缴费月份
     */
    public void addSecurityRecord(Long oid, String userCode, String name, SecurityRecordEntity securityRecordEntity, Date operateTime, Integer type) {
        String startDay = DateUtils.format(operateTime, "yyyy-MM") + "-01 00:00:00";
        String endDay = DateUtils.format(operateTime, "yyyy-MM") + "-31 23:59:59";
        EmployeeSecurityEntity employeeSecurityEntity = employeeSecurityDao.selectOne(new QueryWrapper<EmployeeSecurityEntity>().eq("oid", oid).eq("is_delete", 0));
        //获取方案对应社保信息
        Map<Integer, SecurityItemEntity> securityMap = jobController.securityMap.get(employeeSecurityEntity.getSecurityId());

//        SecurityEntity securityEntity = securityDao.selectById(employeeSecurityEntity.getSecurityId());
        //查询当月是否有未处理的缴费记录
        SecurityRecordEntity oldRecord = securityRecordService.getByOidAndType(oid, 0, startDay, endDay);
        //存在未处理的缴费记录，设置对应recordId更新记录
        if (!ObjectUtils.isEmpty(oldRecord)) {
            securityRecordEntity.setRecordId(oldRecord.getRecordId());
        }
        //社保各项明细
        SecurityItemEntity endowmentItem = securityMap.get(SecurityConst.ITEM_TYPE_ENDOWMENT);//养老保险
        SecurityItemEntity unemploymentItem = securityMap.get(SecurityConst.ITEM_TYPE_UNEMPLOYMENT);//失业保险
        SecurityItemEntity medicalItem = securityMap.get(SecurityConst.ITEM_TYPE_MEDICAL);//医疗保险
        SecurityItemEntity injuryItem = securityMap.get(SecurityConst.ITEM_TYPE_INJURY);//工伤保险
        SecurityItemEntity largerMedicalItem = securityMap.get(SecurityConst.ITEM_TYPE_LARGER_MEDICAL);//大额医疗
        SecurityItemEntity maternityItem = securityMap.get(SecurityConst.ITEM_TYPE_MATERNITY);//生育险
        SecurityItemEntity disabledItem = securityMap.get(SecurityConst.ITEM_TYPE_DISABLED);//残疾保障金
        BigDecimal personCostTotal = new BigDecimal(0);
        BigDecimal orgCostTotal = new BigDecimal(0);
        //根据社保方案以及基数计算跟项明细
        SecurityItemDto endowment = handleSecurityItem(endowmentItem, SecurityConst.ITEM_TYPE_ENDOWMENT, employeeSecurityEntity.getEndowmentInsurance());
        SecurityItemDto unemployment = handleSecurityItem(unemploymentItem, SecurityConst.ITEM_TYPE_UNEMPLOYMENT, employeeSecurityEntity.getUnemploymentInsurance());
        SecurityItemDto medical = handleSecurityItem(medicalItem, SecurityConst.ITEM_TYPE_MEDICAL, employeeSecurityEntity.getMedicalInsurance());
        SecurityItemDto injury = handleSecurityItem(injuryItem, SecurityConst.ITEM_TYPE_INJURY, employeeSecurityEntity.getInjuryInsurance());
        SecurityItemDto largerMedical = handleSecurityItem(largerMedicalItem, SecurityConst.ITEM_TYPE_LARGER_MEDICAL, employeeSecurityEntity.getLargerMedical());
        SecurityItemDto maternity = handleSecurityItem(maternityItem, SecurityConst.ITEM_TYPE_MATERNITY, employeeSecurityEntity.getMaternityInsurance());
        SecurityItemDto disabled = handleSecurityItem(disabledItem, SecurityConst.ITEM_TYPE_DISABLED, employeeSecurityEntity.getDisabledEmployment());
        //将各项明细存入表中
        //养老保险
        securityRecordEntity.setEndowmentInsuranceOrg(endowment.getOrgCost());
        securityRecordEntity.setEndowmentInsuranceOrgRate(endowment.getOrgRate());
        securityRecordEntity.setEndowmentInsurancePerson(endowment.getPersonCost());
        securityRecordEntity.setEndowmentInsurancePersonRate(endowment.getPersonRate());
        securityRecordEntity.setEndowmentInsuranceBase(endowment.getBase());
        //失业保险
        securityRecordEntity.setUnemploymentInsuranceOrg(unemployment.getOrgCost());
        securityRecordEntity.setUnemploymentInsuranceOrgRate(unemployment.getOrgRate());
        securityRecordEntity.setUnemploymentInsurancePerson(unemployment.getPersonCost());
        securityRecordEntity.setUnemploymentInsurancePersonRate(unemployment.getPersonRate());
        securityRecordEntity.setUnemploymentInsuranceBase(unemployment.getBase());
        //医疗保险
        securityRecordEntity.setMedicalInsuranceOrg(medical.getOrgCost());
        securityRecordEntity.setMedicalInsuranceOrgRate(medical.getOrgRate());
        securityRecordEntity.setMedicalInsurancePerson(medical.getPersonCost());
        securityRecordEntity.setMedicalInsurancePersonRate(medical.getPersonRate());
        securityRecordEntity.setMedicalInsuranceBase(medical.getBase());
        //工伤保险
        securityRecordEntity.setInjuryInsuranceOrg(injury.getOrgCost());
        securityRecordEntity.setInjuryInsuranceOrgRate(injury.getOrgRate());
        securityRecordEntity.setInjuryInsurancePerson(injury.getPersonCost());
        securityRecordEntity.setInjuryInsurancePersonRate(injury.getPersonRate());
        securityRecordEntity.setInjuryInsuranceBase(injury.getBase());
        //大额医疗保险
        securityRecordEntity.setLargerMedicalOrg(largerMedical.getOrgCost());
        securityRecordEntity.setLargerMedicalOrgRate(largerMedical.getOrgRate());
        securityRecordEntity.setLargerMedicalPerson(largerMedical.getPersonCost());
        securityRecordEntity.setLargerMedicalPersonRate(largerMedical.getPersonRate());
        securityRecordEntity.setLargerMedicalBase(largerMedical.getBase());
        //生育保险
        securityRecordEntity.setMaternityInsuranceOrg(maternity.getOrgCost());
        securityRecordEntity.setMaternityInsuranceOrgRate(maternity.getOrgRate());
        securityRecordEntity.setMaternityInsurancePerson(maternity.getPersonCost());
        securityRecordEntity.setMaternityInsurancePersonRate(maternity.getPersonRate());
        securityRecordEntity.setMaternityInsuranceBase(maternity.getBase());
        //残疾保障金
        securityRecordEntity.setDisabledEmploymentOrg(disabled.getOrgCost());
        securityRecordEntity.setDisabledEmploymentOrgRate(disabled.getOrgRate());
        securityRecordEntity.setDisabledEmploymentPerson(disabled.getPersonCost());
        securityRecordEntity.setDisabledEmploymentPersonRate(disabled.getPersonRate());
        securityRecordEntity.setDisabledEmploymentBase(disabled.getBase());
        //个人缴费合计
        personCostTotal = injury.getPersonCost().add(largerMedical.getPersonCost()).add(medical.getPersonCost()).
                add(unemployment.getPersonCost().add(endowment.getPersonCost())).add(maternity.getPersonCost())
                .add(disabled.getPersonCost());
        securityRecordEntity.setPersonCostTotal(personCostTotal);
        //公司缴费合计
        orgCostTotal = injury.getOrgCost().add(largerMedical.getOrgCost()).add(medical.getOrgCost()).
                add(unemployment.getOrgCost()).add(endowment.getOrgCost()).add(maternity.getOrgCost()).
                add(disabled.getOrgCost());
        securityRecordEntity.setOrgCostTotal(orgCostTotal);
        securityRecordEntity.setSalaryCost(personCostTotal);
        securityRecordEntity.setOperateName(name);
        securityRecordEntity.setOperateCode(userCode);
        securityRecordEntity.setOperateTime(operateTime);
        securityRecordEntity.setType(type);
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(oid);
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            return;
        }
//        securityRecordEntity.setOrgId(employeeInfoEntity.getOrgId());
        securityRecordEntity.setUnitId(employeeInfoEntity.getUnitId());
        saveOrUpdateSecurityRecord(securityRecordEntity);
    }

    /**
     * 处理社保方案子项明细
     *
     * @param entity
     * @param type
     * @param base
     * @return
     */
    private SecurityItemDto handleSecurityItem(SecurityItemEntity entity, Integer type, BigDecimal base) {
        SecurityItemDto itemDto = new SecurityItemDto();
        itemDto.setOrgCost(new BigDecimal(0));
        itemDto.setPersonCost(new BigDecimal(0));
        BigDecimal percent = new BigDecimal(100);
        BigDecimal personCost = new BigDecimal(0);
        BigDecimal orgCost = new BigDecimal(0);
        if (ObjectUtils.isEmpty(base)) {
            base = new BigDecimal(0);
        }
        itemDto.setBase(base);
        if (!ObjectUtils.isEmpty(entity)) {
            //固定缴费
            if (SecurityConst.IS_FIXED_TRUE.equals(entity.getIsFixed())) {
                if (!ObjectUtils.isEmpty(entity.getOrgFixedAmount())) {
                    orgCost = entity.getOrgFixedAmount();
                }
                if (!ObjectUtils.isEmpty(entity.getPersonalFixedAmount())) {
                    personCost = entity.getPersonalFixedAmount();
                }
                itemDto.setOrgCost(orgCost);
                itemDto.setPersonCost(personCost);
                itemDto.setType(type);
            }
            //比例缴费
            else {
                itemDto.setOrgRate(entity.getOrgRate());
                itemDto.setPersonRate(entity.getPersonalRate());

                if (!ObjectUtils.isEmpty(entity.getPersonalRate())) {
                    personCost = base.multiply(entity.getPersonalRate()).divide(percent);
                }
                if (!ObjectUtils.isEmpty(entity.getOrgRate())) {
                    orgCost = base.multiply(entity.getOrgRate()).divide(percent);
                }
                //设置个人四舍五入位数
                if (!ObjectUtils.isEmpty(entity.getPersonalFormat())) {
                    BigDecimal person = personCost.setScale(entity.getPersonalFormat(), BigDecimal.ROUND_HALF_UP);
                    itemDto.setPersonCost(person);
                } else {
                    itemDto.setPersonCost(personCost);
                }
                //设置公司四舍五入位数
                if (!ObjectUtils.isEmpty(entity.getOrgFormat())) {
                    BigDecimal org = orgCost.setScale(entity.getOrgFormat(), BigDecimal.ROUND_HALF_UP);
                    itemDto.setOrgCost(org);
                } else {
                    itemDto.setOrgCost(orgCost);
                }
            }
        }
        String securityName = SecurityConst.typeName.get(type);
        itemDto.setItemName(securityName);

        return itemDto;
    }

    @PostMapping("/saveOrUpdateSecurityRecord")
    @ApiOperation("保存/更新社保缴费记录")
    @SysAuthorityLog(value = "保存/更新社保缴费记录")
    @Transactional
    @PreAuthorize("hasAuthority('emp:securityCost:update')")
    public R saveOrUpdateSecurityRecord(@RequestBody @Valid SecurityRecordEntity securityRecordEntity) {
        if (ObjectUtils.isEmpty(securityRecordEntity.getRecordId())) {
            securityRecordEntity.setRecordId(snowflakeIdWorker.nextId());
            securityRecordService.saveE(securityRecordEntity);
        } else {
            securityRecordService.updateByIdE(securityRecordEntity);
        }

        return R.ok();
    }

    @PostMapping("/saveOrUpdateFundsRecord")
    @ApiOperation("保存/更新公积金缴费记录")
    @SysAuthorityLog(value = "保存/更新公积金缴费记录")
    @Transactional
    @PreAuthorize("hasAuthority('emp:securityCost:update')")
    public R saveOrUpdateFundsRecord(@RequestBody @Valid FundsRecordEntity fundsRecordEntity) {
        if (ObjectUtils.isEmpty(fundsRecordEntity.getRecordId())) {
            fundsRecordEntity.setRecordId(snowflakeIdWorker.nextId());
            fundsRecordService.saveE(fundsRecordEntity);
        } else {
            fundsRecordService.updateByIdE(fundsRecordEntity);
        }

        return R.ok();
    }

    @PostMapping("/getSecurityRecordList")
    @ApiOperation("社保缴费记录")
    @PreAuthorize("hasAuthority('emp:socialSecurity:update')")
    public R<PageResult<SecurityRecordDto>> getSecurityRecordList(@RequestBody @Valid SecurityRecordVo securityRecordVo, HttpServletRequest request) throws Exception {
        String time = "";
        String endTime = "";
        //获取当前用户角色下公司Id
//        R checkR = loginController.checkOrgPermission(request,null,false);
//        if(!R.isOk.equals(checkR.getStatus())){
//            return checkR;
//        }
//        List<Long> orgIds = (List<Long>) checkR.getData();

        R checkC = loginController.checkContractPermission(request);
        if (!R.isOk.equals(checkC.getStatus())) {
            return checkC;
        }
        List<ContractSubGroupEntity> contractSubs = (List<ContractSubGroupEntity>) checkC.getData();
        ArrayList<Long> contractGoupIds = new ArrayList<Long>();
        for (ContractSubGroupEntity item : contractSubs) {
            contractGoupIds.add(item.getId());
        }

        if (!ObjectUtils.isEmpty(securityRecordVo.getOperateTime())) {
            time = DateUtils.format(securityRecordVo.getOperateTime(), "yyyy-MM") + "-01 00:00:00";
            endTime = DateUtils.format(securityRecordVo.getOperateTime(), "yyyy-MM") + "-31 23:59:59";
        }else{
            time = DateUtils.getBeginDayOfMonth() + " 00:00:00";
            endTime = DateUtils.getLastDayOfMonth() + " 23:59:59";
        }
        PageResult<SecurityRecordDto> recordMap = securityRecordService
                .getRecordList(time, endTime, securityRecordVo.getIsCheck(),
                        securityRecordVo.getIsConfirm(), securityRecordVo.getType(),
                        securityRecordVo.getUnitName(), securityRecordVo.getCityName(), null,
                        securityRecordVo.getName(), contractGoupIds//社保组
                        , securityRecordVo.getUnitId(),
                        securityRecordVo.getPageNum(), securityRecordVo.getPageSize());

        return R.ok(recordMap);
    }

    /*@PostMapping("/getFundsRecordList")
    @ApiOperation("公积金缴费记录")
    @PreAuthorize("hasAuthority('emp:socialSecurity:update')")
    public R<PageResult<FundsRecordDto>> getFundsRecordList(@RequestBody @Valid SecurityRecordVo securityRecordVo,HttpServletRequest request)throws Exception{
        String time = "";
        String endTime = "";
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        if(!ObjectUtils.isEmpty(securityRecordVo.getOperateTime())){
            time = DateUtils.format(securityRecordVo.getOperateTime(),"yyyy-MM")+"-01 00:00:00";
            endTime = DateUtils.format(securityRecordVo.getOperateTime(),"yyyy-MM")+"-31 23:59:59";
        }
        PageResult<FundsRecordDto> recordMap = fundsRecordService.getRecordList(time,endTime,securityRecordVo.getIsCheck(),
                securityRecordVo.getIsConfirm(),securityRecordVo.getType(),
                securityRecordVo.getUnitName(),securityRecordVo.getCityName(),null,
                securityRecordVo.getName(),orgIds,
                securityRecordVo.getPageNum(),securityRecordVo.getPageSize());

        return  R.ok(recordMap);
    }*/


    @PostMapping("/getSecurityEmployeeInfo")
    @ApiOperation("获取方案员工列表")
    @PreAuthorize("hasAuthority('emp:securityEmp:update')")
    public R<List<EmployeeSecurityEntity>> getSecurityEmployeeInfo(String securityId, String fundsId) {
        Long fund = null;
        Long security = null;
        if (!StringUtils.isEmpty(securityId)) {
            security = Long.parseLong(securityId);
        }
        if (!StringUtils.isEmpty(fundsId)) {
            fund = Long.parseLong(fundsId);
        }
        List<EmployeeSecurityDto> list = employeeSecurityService.getUserSecurityList(security, fund);
        for (EmployeeSecurityDto dto : list) {
           /* Map<Long, String> orgMap = jobController.orgMap;
            System.out.println(orgMap);
            dto.setOrgname(jobController.orgMap.get(dto.getOrgId()));*/
        }
        return R.ok(list);
    }

    @DeleteMapping("/deleteEmployeeSecurity")
    @ApiOperation("根据类型删除员工社保公积金方案")
    @SysAuthorityLog(value = "根据类型删除员工社保公积金方案")
    @PreAuthorize("hasAuthority('emp:securityEmp:update')")
    @Transactional
    public R deleteEmployeeSecurity(Integer type, String employeeSecurityId, String securityId, String oid, HttpServletRequest request) throws Exception {


        SecurityChangeVo changeVo = new SecurityChangeVo();
        changeVo.setOperateTime(new Date());
        changeVo.setSecurityId(Long.parseLong(securityId));
        changeVo.setType(SecurityConst.CHANGE_TYPE_REDUCE);
        changeVo.setOid(Long.parseLong(oid));
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(Long.parseLong(oid));
        if (!ObjectUtils.isEmpty(employeeInfoEntity)) {
            changeVo.setOrgId(employeeInfoEntity.getOrgId());
            changeVo.setUnitId(employeeInfoEntity.getUnitId());
        }
        changeSecurity(changeVo, request, null, null);
        if (SecurityConst.ITEM_TYPE_ENDOWMENT.equals(type)) {
            employeeSecurityDao.deleteSecurityById(Long.parseLong(employeeSecurityId));
        } else {
            employeeSecurityDao.deleteFundsById(Long.parseLong(employeeSecurityId));
        }
        //更新减社保方案人数
        SecurityEntity securityEntity = securityService.getByIdE(Long.parseLong(securityId));
        if (!ObjectUtils.isEmpty(securityEntity)) {
            securityEntity.setNumber(securityEntity.getNumber() - 1);
            securityService.updateByIdE(securityEntity);
        }

        return R.ok();
    }

    @PostMapping("/getSecurityChangeList")
    @ApiOperation("获取方案变更列表")
    @PreAuthorize("hasAuthority('emp:securityChage:get')")
    public R<PageResult<SecurityChangeDto>> getSecurityChangeList(@RequestBody @Valid SecurityChangeListVo vo, HttpServletRequest request) throws Exception {
        String dateStr = null;
        //获取当前用户角色下合同主体Id
        R checkR = loginController.checkContractPermission(request);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<ContractSubGroupEntity> contractSubs = (List<ContractSubGroupEntity>) checkR.getData();
        ArrayList<Long> contractIds = new ArrayList<Long>();
        for (ContractSubGroupEntity item : contractSubs) {
            contractIds.add(item.getId());
        }

        if (!ObjectUtils.isEmpty(vo.getOperationTime())) {
            dateStr = DateUtils.format(vo.getOperationTime(), "yyyy-MM-dd") + " 23:59:59";
        }

        PageResult<SecurityChangeDto> result = securityChangeService.getChangeListAuth(vo.getSecurityId(),
                dateStr, vo.getType(), vo.getName(), vo.getOperateName(), vo.getSecurityType(), contractIds,
                vo.getPageNum(), vo.getPageSize());

        return R.ok(result);
    }

//    @PostMapping("/getSecurityChangeList")
//    @ApiOperation("获取方案变更列表")
//    @PreAuthorize("hasAuthority('emp:securityChage:get')")
//    public R<PageResult<SecurityChangeDto>> getSecurityChangeList(@RequestBody @Valid SecurityChangeListVo vo,HttpServletRequest request)throws Exception{
//        String dateStr = null;
//        //获取当前用户角色下公司Id
//        R checkR = loginController.checkOrgPermission(request,null,false);
//        if(!R.isOk.equals(checkR.getStatus())){
//            return checkR;
//        }
//        List<Long> orgIds = (List<Long>) checkR.getData();
//        if(!ObjectUtils.isEmpty(vo.getOperationTime())){
//            dateStr =   DateUtils.format(vo.getOperationTime(),"yyyy-MM-dd")+" 23:59:59";
//        }
//
//        PageResult<SecurityChangeDto> result = securityChangeService.getChangeList(vo.getSecurityId(),
//                dateStr,vo.getType(),vo.getName(),vo.getOperateName(),vo.getSecurityType(),orgIds,
//                vo.getPageNum(),vo.getPageSize());
//
//        return R.ok(result);
//    }


    /**
     * @param vo
     * @return
     */
    @PostMapping("/saveOrUpdateEmployeeSecurity")
    @ApiOperation("保存个人社保公积金方案")
    @SysAuthorityLog(value = "保存个人社保公积金方案")
    @Transactional
    @PreAuthorize("hasAuthority('emp:securityEmp:update')")
    public R<EmployeeSecurityEntity> saveOrUpdateEmployeeSecurity(@RequestBody @Valid EmployeeSecurityVo vo, HttpServletRequest request, boolean isUpdate) throws Exception {
        //查出公积金所有明细
        List<SecurityItemEntity> itemEntities = securityItemService.getItemBySecurityId(vo.getTypeId());
        EmployeeSecurityEntity employeeSecurityEntity = employeeSecurityDao.selectOne(new QueryWrapper<EmployeeSecurityEntity>().eq("oid", vo.getOid()).eq("is_delete", 0));
        if (!isUpdate && !ObjectUtils.isEmpty(employeeSecurityEntity) && ObjectUtils.isEmpty(vo.getId())) {
            if (SecurityConst.SECURITY_TYPE_FUNDS.equals(vo.getType()) && !ObjectUtils.isEmpty(employeeSecurityEntity.getFundsId()) && ObjectUtils.isEmpty(vo.getId())) {
                SecurityEntity securityEntity = securityService.getByIdE(employeeSecurityEntity.getFundsId());
                return R.error("该用户已经分配有" + securityEntity.getUnitName() + "方案， 无法新增！");
            } else if (!SecurityConst.SECURITY_TYPE_FUNDS.equals(vo.getType()) && !ObjectUtils.isEmpty(employeeSecurityEntity.getSecurityId()) && ObjectUtils.isEmpty(vo.getId())) {
                SecurityEntity securityEntity = securityService.getByIdE(employeeSecurityEntity.getSecurityId());
                return R.error("该用户已经分配有" + securityEntity.getUnitName() + "方案， 无法新增！");
            }
        }
        //遍历添加的人员信息
//        for(EmployeeSecurityVo vo:voList.getVo()){
        EmployeeSecurityEntity user = BeanUtilsMabach.doToDto(vo, EmployeeSecurityEntity.class);
        if (!ObjectUtils.isEmpty(employeeSecurityEntity)) {
            user.setId(employeeSecurityEntity.getId());
        }
        if (SecurityConst.ITEM_TYPE_ENDOWMENT.equals(vo.getType())) {
            user.setSecurityId(vo.getTypeId());
            if (itemEntities.size() == 0) {
                return R.error("社保缴纳项目未配置！");
            }
            for (SecurityItemEntity item : itemEntities) {
                if (SecurityConst.IS_FIXED_TRUE.equals(item.getIsFixed())) {
                    continue;
                }
                BigDecimal insurance = item.getLowerLimit();
                String type = "";
                if (SecurityConst.ITEM_TYPE_ENDOWMENT.equals(item.getSecurityType())) {
                    if (ObjectUtils.isEmpty(user.getEndowmentInsurance())) {
                        user.setEndowmentInsurance(insurance);
                    } else {
                        insurance = user.getEndowmentInsurance();
                    }
                    type = "养老保险";
                } else if (SecurityConst.ITEM_TYPE_MEDICAL.equals(item.getSecurityType())) {
                    if (ObjectUtils.isEmpty(user.getMedicalInsurance())) {
                        user.setMedicalInsurance(insurance);
                    } else {
                        insurance = user.getMedicalInsurance();
                    }
                    type = "医疗保险";
                } else if (SecurityConst.ITEM_TYPE_INJURY.equals(item.getSecurityType())) {
                    if (ObjectUtils.isEmpty(user.getInjuryInsurance())) {
                        user.setInjuryInsurance(insurance);
                    } else {
                        insurance = user.getInjuryInsurance();
                    }
                    type = "工伤保险";
                } else if (SecurityConst.ITEM_TYPE_LARGER_MEDICAL.equals(item.getSecurityType())) {
                    if (ObjectUtils.isEmpty(user.getLargerMedical())) {
                        user.setLargerMedical(insurance);
                    } else {
                        insurance = user.getLargerMedical();
                    }
                    type = "大额医疗保险";
                } else if (SecurityConst.ITEM_TYPE_MATERNITY.equals(item.getSecurityType())) {
                    if (ObjectUtils.isEmpty(user.getMaternityInsurance())) {
                        user.setMaternityInsurance(insurance);
                    } else {
                        insurance = user.getMaternityInsurance();
                    }
                    type = "生育保险";
                } else if (SecurityConst.ITEM_TYPE_DISABLED.equals(item.getSecurityType())) {
                    if (ObjectUtils.isEmpty(user.getDisabledEmployment())) {
                        user.setDisabledEmployment(insurance);
                    } else {
                        insurance = user.getDisabledEmployment();
                    }
                    type = "残疾保障金";
                } else {
                    if (ObjectUtils.isEmpty(user.getUnemploymentInsurance())) {
                        user.setUnemploymentInsurance(insurance);
                    } else {
                        insurance = user.getUnemploymentInsurance();
                    }
                    type = "失业保险";
                }
                if (ObjectUtils.isEmpty(insurance) || insurance.compareTo(item.getLowerLimit()) < 0 || insurance.compareTo(item.getUpperLimit()) > 0) {
                    return R.error(vo.getName() + "设定的" + type + "基数范围不符合要求！");
                }
            }
        } else {
            if (itemEntities.size() <= 0) {
                return R.error("公积金方案不存在！");
            }
            BigDecimal insurance;
            String type;
            for (SecurityItemEntity item : itemEntities) {
                insurance = item.getLowerLimit();
                if (SecurityConst.ITEM_TYPE_FUNDS.equals(item.getSecurityType())) {
                    if (ObjectUtils.isEmpty(user.getReservedFunds())) {
                        user.setReservedFunds(insurance);
                    } else {
                        insurance = user.getReservedFunds();
                    }
                    type = "公积金";
                } else {
                    if (ObjectUtils.isEmpty(user.getOfferFunds())) {
                        user.setOfferFunds(insurance);
                    } else {
                        insurance = user.getOfferFunds();
                    }
                    type = "补充公积金";
                }
                if (ObjectUtils.isEmpty(insurance) || insurance.compareTo(item.getLowerLimit()) < 0 || insurance.compareTo(item.getUpperLimit()) > 0) {
                    return R.error(vo.getName() + "设定的" + type + "基数范围不符合要求！");
                }
            }


            user.setFundsId(vo.getTypeId());
        }

        if (!ObjectUtils.isEmpty(user.getId())) {
            employeeSecurityService.updateByIdE(user);
        } else {
            employeeSecurityService.saveE(user);
        }
        if (ObjectUtils.isEmpty(vo.getId())) {
            //插入新增记录
            SecurityChangeVo changeVo = new SecurityChangeVo();
            EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(vo.getOid());
            if (!ObjectUtils.isEmpty(employeeInfoEntity)) {
                changeVo.setOrgId(employeeInfoEntity.getOrgId());
                changeVo.setUnitId(employeeInfoEntity.getUnitId());
            }
            changeVo.setOperateTime(new Date());
            changeVo.setSecurityId(vo.getTypeId());
            changeVo.setType(SecurityConst.CHANGE_TYPE_ADD);
            changeVo.setOid(user.getOid());

            changeSecurity(changeVo, request, null, null);
            //更新入社保方案人数
            SecurityEntity securityEntity = securityService.getByIdE(vo.getTypeId());
            if (!ObjectUtils.isEmpty(securityEntity)) {
                securityEntity.setNumber(securityEntity.getNumber() + 1);
                securityService.updateByIdE(securityEntity);
            }
        } else {
            SecurityChangeVo changeVo = new SecurityChangeVo();
            changeVo.setOperateTime(new Date());
            changeVo.setSecurityId(vo.getTypeId());
            changeVo.setType(SecurityConst.CHANGE_TYPE_UPDATE);
            changeVo.setOid(user.getOid());
            EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(vo.getOid());
            if (!ObjectUtils.isEmpty(employeeInfoEntity)) {
                changeVo.setOrgId(employeeInfoEntity.getOrgId());
                changeVo.setUnitId(employeeInfoEntity.getUnitId());
            }
            changeSecurity(changeVo, request, null, null);
        }
//        }
        return R.ok(user);
    }


    @PostMapping("/updateRecordStatus")
    @ApiOperation("更新汇缴/确认状态")
    @SysAuthorityLog(value = "更新汇缴/确认状态")
    @Transactional
    @PreAuthorize("hasAuthority('emp:securityCost:update')")
    public R updateRecordStatus(@RequestBody @Valid SecurityRecordUpdateVo vo, HttpServletRequest request) throws Exception {
        R uR = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) uR.getData();
        String userCode = user.getString("usercode");
        String name = user.getString("name");
        if (RECORD_ALL.equals(vo.getIsAll())) {
            List<SecurityEntity> securityList = securityDao.selectList(new QueryWrapper<SecurityEntity>().eq("is_delete", 0).eq("contract_main_id", vo.getUnitId()).eq("type", vo.getType()));
            if (CollectionUtils.isEmpty(securityList)) {
                return R.error("方案不存在,无法确认汇缴！");
            }
            SecurityEntity securityEntity = securityList.get(0);
            if (!SECURITY_TYPE_FUNDS.equals(vo.getType())) {
                List<String> list = securityRecordService.getIdBySecurityId(securityEntity.getSecurityId(), vo.getStatus());
                if (!CollectionUtils.isEmpty(list))
                    vo.setRecordId(list.toArray(new String[list.size() - 1]));
            } else {
                List<String> list = fundsRecordService.getIdBySecurityId(securityEntity.getSecurityId(), vo.getStatus());
                if (!CollectionUtils.isEmpty(list))
                    vo.setRecordId(list.toArray(new String[list.size() - 1]));
            }
        }
        if (ObjectUtils.isEmpty(vo.getRecordId())) {
            return R.error("当前方案不存在需要处理数据");
        }
        R isConfirm = isConfirm(vo);
        //判断是否已经被确认过
        if (!isConfirm.getFlag()) {
            return isConfirm;
        }
        Map<Long, Object> securityMap = (Map<Long, Object>) isConfirm.getData();
        Date date = new Date();
        Map<Long, SecurityBatchEntity> batchEntityMap = new HashMap<>();
        Map<String, List> memberMap = new HashMap<>();


        for (String id : vo.getRecordId()) {
            Long recordId = Long.parseLong(id);
            //公积金
            if (SECURITY_TYPE_FUNDS.equals(vo.getType())) {
                FundsRecordEntity fundsRecordEntity = fundsRecordService.getByIdE(recordId);
                fundsRecordEntity.setOperateCode(userCode);
                fundsRecordEntity.setOperateName(name);
                if (RECORD_TYPE_CHECK.equals(vo.getStatus())) {
                    fundsRecordEntity.setIsCheck(1);
                } else {
                    fundsRecordEntity.setIsConfirm(1);
                    fundsRecordEntity.setConfirmTime(date);
                    batchEntityMap = handleBatchMap(batchEntityMap, securityMap, vo.getType(), recordId, name, userCode, date, memberMap, fundsRecordEntity.getOid());
                }
                fundsRecordService.updateByIdE(fundsRecordEntity);
            } else {
                SecurityRecordEntity recordEntity = securityRecordService.getByIdE(recordId);
                recordEntity.setOperateName(name);
                recordEntity.setOperateCode(userCode);
                if (RECORD_TYPE_CHECK.equals(vo.getStatus())) {
                    recordEntity.setIsCheck(1);
                } else {
                    recordEntity.setIsConfirm(1);
                    recordEntity.setConfirmTime(date);
                    batchEntityMap = handleBatchMap(batchEntityMap, securityMap, vo.getType(), recordId, name, userCode, date, memberMap, recordEntity.getOid());
                }
                securityRecordService.updateByIdE(recordEntity);
            }

        }
        Iterator<Map.Entry<Long, SecurityBatchEntity>> entries = batchEntityMap.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<Long, SecurityBatchEntity> entry = entries.next();
            securityBatchService.updateByIdE(entry.getValue());
        }
        Iterator<Map.Entry<String, List>> entryIterator = memberMap.entrySet().iterator();
        //处理当前批次内方案内人员汇总
        while (entryIterator.hasNext()) {
            Map.Entry<String, List> entry = entryIterator.next();
            if (!SECURITY_TYPE_FUNDS.equals(vo.getType())) {
                List<SecurityRecordEntity> list = entry.getValue();
                neusoftSecurityService.uploadSecurity(list, date);
            } else {
                List<FundsRecordEntity> list = entry.getValue();
                neusoftSecurityService.uploadFunds(list, date);
            }
        }
        return R.ok();
    }

    private Map<Long, SecurityBatchEntity> handleBatchMap(Map<Long, SecurityBatchEntity> batchEntityMap, Map<Long, Object> securityMap, Integer type, Long id,
                                                          String name, String userCode, Date date, Map<String, List> memberMap, Long oid) {
        Object record = securityMap.get(id);
        SecurityBatchDto recordEntity = BeanUtilsMabach.doToDto(record, SecurityBatchDto.class);
        SecurityBatchEntity batchEntity = null;
        if (ObjectUtils.isEmpty(batchEntityMap.get(recordEntity.getSecurityId()))) {
            batchEntity = new SecurityBatchEntity();
            batchEntity.setApplyer(name);
            batchEntity.setApplyerCode(userCode);
            batchEntity.setCityName(recordEntity.getCityName());
            batchEntity.setConfirmTime(date);
            batchEntity.setNumber(1);
            batchEntity.setType(type);
            batchEntity.setOperateTime(date);
            batchEntity.setOrgCost(recordEntity.getOrgCostTotal());
            batchEntity.setPersonCost(recordEntity.getPersonCostTotal());
            batchEntity.setUnitName(recordEntity.getUnitName());
//                        batchEntity.setUnitId(re);
            batchEntity.setTotalCost(recordEntity.getSalaryCost());
            batchEntity.setOrgName(recordEntity.getOrgName());
            batchEntity.setSecurityId(recordEntity.getSecurityId());
            securityBatchService.saveE(batchEntity);
            List list = new ArrayList();
            list.add(record);
            memberMap.put(batchEntity.getId() + "_" + oid, list);
//            batchEntity.set
        } else {
            batchEntity = batchEntityMap.get(recordEntity.getSecurityId());
            //排除补缴人数
            if (StringUtils.isEmpty(memberMap.get(batchEntity.getId() + "_" + oid))) {
                batchEntity.setNumber(batchEntity.getNumber() + 1);
                List list = new ArrayList();
                list.add(record);
                memberMap.put(batchEntity.getId() + "_" + oid, list);

            } else {
                memberMap.get(batchEntity.getId() + "_" + oid).add(record);
            }

            batchEntity.setOrgCost(recordEntity.getOrgCostTotal().add(batchEntity.getOrgCost()));
            batchEntity.setPersonCost(recordEntity.getPersonCostTotal().add(batchEntity.getPersonCost()));
            batchEntity.setTotalCost(batchEntity.getOrgCost().add(batchEntity.getPersonCost()));
        }
        SecurityBatchGroupEntity groupEntity = new SecurityBatchGroupEntity();
        groupEntity.setCreateTime(new Date());
        groupEntity.setBatchId(batchEntity.getId());
        groupEntity.setRecordId(id);
        securityBatchGroupService.saveE(groupEntity);
        batchEntityMap.put(recordEntity.getSecurityId(), batchEntity);
        return batchEntityMap;
    }

    @PostMapping("/supplementarySecurity")
    @ApiOperation("社保补缴")
    @PreAuthorize("hasAuthority('emp:socialSecurity:update')")
    @Transactional
    public R supplementarySecurity(@RequestBody @Valid SecuritySupplementaryVo vo, HttpServletRequest request) throws Exception {
        EmployeeSecurityEntity employeeSecurityEntity = employeeSecurityDao.selectOne(new QueryWrapper<EmployeeSecurityEntity>().eq("oid", vo.getOid()));
        if (ObjectUtils.isEmpty(employeeSecurityEntity)) {
            return R.error("该员工未分配方案，无法补缴！");
        }
        Long id = employeeSecurityEntity.getSecurityId();
        if (ObjectUtils.isEmpty(id)) {
            return R.error("该员工未分配方案，无法补缴！");
        }
        String errorMsg = "";
        BigDecimal orgCostTotal = new BigDecimal(0);
        BigDecimal personCostTotal = new BigDecimal(0);
        R uR = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) uR.getData();
        String userCode = user.getString("usercode");
        String name = user.getString("name");
        SecurityRecordEntity record = BeanUtilsMabach.doToDto(vo, SecurityRecordEntity.class);
        SecurityEntity securityEntity = securityService.getByIdE(id);
        record.setOperateTime(vo.getTime());
        record.setCreateTime(new Date());
        record.setUnitName(securityEntity.getUnitName());
        record.setCityName(securityEntity.getCityName());
        record.setType(0);
        record.setSecurityId(id);
        String startDay = DateUtils.format(record.getOperateTime(), "yyyy-MM") + "-01 00:00:00";
        String endDay = DateUtils.format(record.getOperateTime(), "yyyy-MM") + "-31 23:59:59";
        Long unitId = null;
        //查询当月是否有未处理的缴费记录
        SecurityRecordEntity oldRecord = securityRecordService.getByOidAndType(vo.getOid(), 1, startDay, endDay);
        if (!ObjectUtils.isEmpty(oldRecord)) {
            errorMsg = "当月已有确认过的缴费记录，无法补缴!";
        } else {
            EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(vo.getOid());
            if (ObjectUtils.isEmpty(employeeInfoEntity)) {
                return R.error();
            }
            unitId = employeeInfoEntity.getUnitId();
            SecurityRecordEntity old = securityRecordService.getByOidAndType(vo.getOid(), 0, startDay, endDay);
            //存在未处理的缴费记录，设置对应recordId更新记录
            if (!ObjectUtils.isEmpty(old)) {
                record.setRecordId(old.getRecordId());
            }
//            record.setOrgId(employeeInfoEntity.getOrgId());
            record.setUnitId(employeeInfoEntity.getUnitId());
            record.setOrgName(jobController.orgMap.get(employeeInfoEntity.getOrgId()));
            record.setOperateName(name);
            record.setOperateTime(vo.getTime());
            record.setOperateCode(userCode);
            personCostTotal = !ObjectUtils.isEmpty(record.getUnemploymentInsurancePerson()) ? record.getUnemploymentInsurancePerson() : new BigDecimal(0);
            personCostTotal = personCostTotal.add(getTotal(record.getDisabledEmploymentPerson(), record.getEndowmentInsurancePerson())).add(
                    getTotal(record.getInjuryInsurancePerson(), record.getLargerMedicalPerson())).
                    add(getTotal(record.getMaternityInsurancePerson(), record.getMedicalInsurancePerson()));
            orgCostTotal = !ObjectUtils.isEmpty(record.getUnemploymentInsuranceOrg()) ? record.getUnemploymentInsuranceOrg() : new BigDecimal(0);
            orgCostTotal = orgCostTotal.add(getTotal(record.getDisabledEmploymentOrg(), record.getEndowmentInsuranceOrg())).add(
                    getTotal(record.getInjuryInsuranceOrg(), record.getLargerMedicalOrg())).
                    add(getTotal(record.getMaternityInsuranceOrg(), record.getMedicalInsuranceOrg()));
            record.setPersonCostTotal(personCostTotal);
            record.setOrgCostTotal(orgCostTotal);
            record.setSalaryCost(personCostTotal);
            saveOrUpdateSecurityRecord(record);
        }
        //添加社保方案补缴记录
        SecurityChangeEntity changeEntity = new SecurityChangeEntity();
        changeEntity.setSecurityId(id);
        changeEntity.setOperationTime(vo.getTime());
        changeEntity.setOid(vo.getOid());
        changeEntity.setType(SecurityConst.CHANGE_TYPE_CHANGE);
        changeEntity.setOperaterCode(userCode);
        changeEntity.setUnitId(unitId);
        changeEntity.setOperateName(name);
        securityChangeService.saveE(changeEntity);
        if (StringUtils.isEmpty(errorMsg)) {
            return R.ok();
        } else {
            return R.error(errorMsg);
        }
    }

    @PostMapping("/supplementaryFunds")
    @ApiOperation("公积金补缴")
    @PreAuthorize("hasAuthority('emp:socialSecurity:update')")
    @Transactional
    public R supplementaryFunds(@RequestBody @Valid SupplementaryFundsVo vo, HttpServletRequest request) throws Exception {
        EmployeeSecurityEntity employeeSecurityEntity = employeeSecurityDao.selectOne(new QueryWrapper<EmployeeSecurityEntity>().eq("oid", vo.getOid()));
        if (ObjectUtils.isEmpty(employeeSecurityEntity)) {
            return R.error("该员工未分配方案，无法补缴！");
        }
        Long id = employeeSecurityEntity.getFundsId();
        if (ObjectUtils.isEmpty(id)) {
            return R.error("该员工未分配方案，无法补缴！");
        }
        String errorMsg = "";
        BigDecimal orgCostTotal = new BigDecimal(0);
        BigDecimal personCostTotal = new BigDecimal(0);
        R uR = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) uR.getData();
        String userCode = user.getString("usercode");
        String name = user.getString("name");
        FundsRecordEntity record = BeanUtilsMabach.doToDto(vo, FundsRecordEntity.class);
        SecurityEntity securityEntity = securityService.getByIdE(id);
        record.setCreateTime(vo.getTime());
        record.setUnitName(securityEntity.getUnitName());
        record.setCityName(securityEntity.getCityName());
        record.setType(0);
        record.setSecurityId(id);
        String startDay = DateUtils.format(record.getCreateTime(), "yyyy-MM") + "-01 00:00:00";
        String endDay = DateUtils.format(record.getCreateTime(), "yyyy-MM") + "-31 23:59:59";
        Long unitId = null;
        //查询当月是否有未处理的缴费记录
        FundsRecordEntity oldRecord = fundsRecordService.getByOidAndType(vo.getOid(), 1, startDay, endDay);
        if (!ObjectUtils.isEmpty(oldRecord)) {
            errorMsg = "当月已有确认过的缴费记录，无法补缴!";
        } else {
            EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(vo.getOid());
            if (ObjectUtils.isEmpty(employeeInfoEntity)) {
                return R.error();
            }
            unitId = employeeInfoEntity.getUnitId();
            FundsRecordEntity old = fundsRecordService.getByOidAndType(vo.getOid(), 0, startDay, endDay);
            //存在未处理的缴费记录，设置对应recordId更新记录
            if (!ObjectUtils.isEmpty(old)) {
                record.setRecordId(old.getRecordId());
            }
//            record.setOrgId(employeeInfoEntity.getOrgId());
            record.setUnitId(employeeInfoEntity.getUnitId());
            record.setOrgName(jobController.orgMap.get(employeeInfoEntity.getOrgId()));
            record.setOperateName(name);
            record.setOperateTime(vo.getTime());
            record.setOperateCode(userCode);
            personCostTotal = getTotal(record.getOfferFundsPerson(), record.getReservedFundsPerson());
            orgCostTotal = getTotal(record.getOfferFundsOrg(), record.getReservedFundsOrg());
            record.setPersonCostTotal(personCostTotal);
            record.setOrgCostTotal(orgCostTotal);
            record.setSalaryCost(personCostTotal);
            saveOrUpdateFundsRecord(record);
        }
        //添加社保方案补缴记录
        SecurityChangeEntity changeEntity = new SecurityChangeEntity();
        changeEntity.setSecurityId(id);
        changeEntity.setOperationTime(vo.getTime());
        changeEntity.setOid(vo.getOid());
        changeEntity.setType(SecurityConst.CHANGE_TYPE_CHANGE);
        changeEntity.setOperaterCode(userCode);
        changeEntity.setOperateName(name);
        changeEntity.setUnitId(unitId);
        securityChangeService.saveE(changeEntity);
        if (StringUtils.isEmpty(errorMsg)) {
            return R.ok();
        } else {
            return R.error(errorMsg);
        }
    }

    @PostMapping("/getSupplementarySecurityPrev")
    @ApiOperation("补缴社保预览")
    @PreAuthorize("hasAuthority('emp:socialSecurity:get')")
    public R<SecurityRecordEntity> getSupplementarySecurityPrev(String oid) {
        EmployeeSecurityEntity employeeSecurityEntity = employeeSecurityDao.selectOne(new QueryWrapper<EmployeeSecurityEntity>().
                eq("oid", Long.parseLong(oid)));
        SecurityEntity securityEntity = securityService.getByIdE(employeeSecurityEntity.getSecurityId());
        List<SecurityItemEntity> items = securityItemDao.selectList(new QueryWrapper<SecurityItemEntity>().eq("security_id", securityEntity.getSecurityId()));
        //获取方案对应社保信息
        Map<Integer, SecurityItemEntity> securityMap = jobController.securityMap.get(employeeSecurityEntity.getSecurityId());
        SecurityRecordEntity securityRecordEntity = new SecurityRecordEntity();
        BigDecimal personTotal = new BigDecimal(0);
        BigDecimal orgTotal = new BigDecimal(0);
        for (SecurityItemEntity item : items) {
            if (SecurityConst.ITEM_TYPE_ENDOWMENT.equals(item.getSecurityType())) {
                SecurityItemEntity endowmentItem = securityMap.get(SecurityConst.ITEM_TYPE_ENDOWMENT);//养老保险
                SecurityItemDto endowment = handleSecurityItem(endowmentItem, SecurityConst.ITEM_TYPE_ENDOWMENT, employeeSecurityEntity.getEndowmentInsurance());
                //养老保险
                securityRecordEntity.setEndowmentInsuranceOrg(endowment.getOrgCost());
                securityRecordEntity.setEndowmentInsuranceOrgRate(endowment.getOrgRate());
                securityRecordEntity.setEndowmentInsurancePerson(endowment.getPersonCost());
                securityRecordEntity.setEndowmentInsurancePersonRate(endowment.getPersonRate());
                personTotal.add(endowment.getPersonCost());
                orgTotal.add(endowment.getOrgCost());
            } else if (SecurityConst.ITEM_TYPE_UNEMPLOYMENT.equals(item.getSecurityType())) {
                SecurityItemEntity unemploymentItem = securityMap.get(SecurityConst.ITEM_TYPE_UNEMPLOYMENT);//失业保险
                SecurityItemDto unemployment = handleSecurityItem(unemploymentItem, SecurityConst.ITEM_TYPE_UNEMPLOYMENT, employeeSecurityEntity.getUnemploymentInsurance());
                //失业保险
                securityRecordEntity.setUnemploymentInsuranceOrg(unemployment.getOrgCost());
                securityRecordEntity.setUnemploymentInsuranceOrgRate(unemployment.getOrgRate());
                securityRecordEntity.setUnemploymentInsurancePerson(unemployment.getPersonCost());
                securityRecordEntity.setUnemploymentInsurancePersonRate(unemployment.getPersonRate());
                personTotal.add(unemployment.getPersonCost());
                orgTotal.add(unemployment.getOrgCost());
            } else if (SecurityConst.ITEM_TYPE_MEDICAL.equals(item.getSecurityType())) {
                SecurityItemEntity medicalItem = securityMap.get(SecurityConst.ITEM_TYPE_MEDICAL);//医疗保险
                SecurityItemDto medical = handleSecurityItem(medicalItem, SecurityConst.ITEM_TYPE_MEDICAL, employeeSecurityEntity.getMedicalInsurance());
                //医疗保险
                securityRecordEntity.setMedicalInsuranceOrg(medical.getOrgCost());
                securityRecordEntity.setMedicalInsuranceOrgRate(medical.getOrgRate());
                securityRecordEntity.setMedicalInsurancePerson(medical.getPersonCost());
                securityRecordEntity.setMedicalInsurancePersonRate(medical.getPersonRate());
                personTotal.add(medical.getPersonCost());
                orgTotal.add(medical.getOrgCost());
            } else if (SecurityConst.ITEM_TYPE_INJURY.equals(item.getSecurityType())) {
                SecurityItemEntity injuryItem = securityMap.get(SecurityConst.ITEM_TYPE_INJURY);//工伤保险
                SecurityItemDto injury = handleSecurityItem(injuryItem, SecurityConst.ITEM_TYPE_INJURY, employeeSecurityEntity.getInjuryInsurance());
                //工伤保险
                securityRecordEntity.setInjuryInsuranceOrg(injury.getOrgCost());
                securityRecordEntity.setInjuryInsuranceOrgRate(injury.getOrgRate());
                securityRecordEntity.setInjuryInsurancePerson(injury.getPersonCost());
                securityRecordEntity.setInjuryInsurancePersonRate(injury.getPersonRate());
                personTotal.add(injury.getPersonCost());
                orgTotal.add(injury.getOrgCost());
            } else if (SecurityConst.ITEM_TYPE_LARGER_MEDICAL.equals(item.getSecurityType())) {
                SecurityItemEntity largerMedicalItem = securityMap.get(SecurityConst.ITEM_TYPE_LARGER_MEDICAL);//大额医疗
                SecurityItemDto largerMedical = handleSecurityItem(largerMedicalItem, SecurityConst.ITEM_TYPE_LARGER_MEDICAL, employeeSecurityEntity.getLargerMedical());
                //大额医疗保险
                securityRecordEntity.setLargerMedicalOrg(largerMedical.getOrgCost());
                securityRecordEntity.setLargerMedicalOrgRate(largerMedical.getOrgRate());
                securityRecordEntity.setLargerMedicalPerson(largerMedical.getPersonCost());
                securityRecordEntity.setLargerMedicalPersonRate(largerMedical.getPersonRate());
                personTotal.add(largerMedical.getPersonCost());
                orgTotal.add(largerMedical.getOrgCost());
            } else if (SecurityConst.ITEM_TYPE_MATERNITY.equals(item.getSecurityType())) {
                SecurityItemEntity maternityItem = securityMap.get(SecurityConst.ITEM_TYPE_MATERNITY);//生育险
                SecurityItemDto maternity = handleSecurityItem(maternityItem, SecurityConst.ITEM_TYPE_MATERNITY, employeeSecurityEntity.getMaternityInsurance());
                //生育保险
                securityRecordEntity.setMaternityInsuranceOrg(maternity.getOrgCost());
                securityRecordEntity.setMaternityInsuranceOrgRate(maternity.getOrgRate());
                securityRecordEntity.setMaternityInsurancePerson(maternity.getPersonCost());
                securityRecordEntity.setMaternityInsurancePersonRate(maternity.getPersonRate());
                personTotal.add(maternity.getPersonCost());
                orgTotal.add(maternity.getOrgCost());
            } else if (SecurityConst.ITEM_TYPE_DISABLED.equals(item.getSecurityType())) {
                SecurityItemEntity disabledItem = securityMap.get(SecurityConst.ITEM_TYPE_LARGER_MEDICAL);//残疾保障金
                SecurityItemDto disabled = handleSecurityItem(disabledItem, SecurityConst.ITEM_TYPE_DISABLED, employeeSecurityEntity.getDisabledEmployment());
                //残疾保障金
                securityRecordEntity.setDisabledEmploymentOrg(disabled.getOrgCost());
                securityRecordEntity.setDisabledEmploymentOrgRate(disabled.getOrgRate());
                securityRecordEntity.setDisabledEmploymentPerson(disabled.getPersonCost());
                securityRecordEntity.setDisabledEmploymentPersonRate(disabled.getPersonRate());
                personTotal.add(disabled.getPersonCost());
                orgTotal.add(disabled.getOrgCost());
            }
        }
        securityRecordEntity.setPersonCostTotal(personTotal);
        securityRecordEntity.setOrgCostTotal(orgTotal);
        return R.ok(securityRecordEntity);
    }


    @PostMapping("/getSupplementaryFundsPrev")
    @ApiOperation("公积金社保预览")
    @PreAuthorize("hasAuthority('emp:socialSecurity:get')")
    public R<FundsRecordEntity> getSupplementaryFundsPrev(String oid) {
        EmployeeSecurityEntity employeeSecurityEntity = employeeSecurityDao.selectOne(new QueryWrapper<EmployeeSecurityEntity>().
                eq("oid", Long.parseLong(oid)));
        SecurityEntity securityEntity = securityService.getByIdE(employeeSecurityEntity.getFundsId());
        List<SecurityItemEntity> items = securityItemDao.selectList(new QueryWrapper<SecurityItemEntity>().eq("security_id", securityEntity.getSecurityId()));
        //获取方案对应社保信息
        Map<Integer, SecurityItemEntity> securityMap = jobController.securityMap.get(employeeSecurityEntity.getSecurityId());
        FundsRecordEntity fundsRecordEntity = new FundsRecordEntity();
        BigDecimal personTotal = new BigDecimal(0);
        BigDecimal orgTotal = new BigDecimal(0);
        for (SecurityItemEntity item : items) {
            if (item.getSecurityType().equals(SecurityConst.ITEM_TYPE_FUNDS)) {
                SecurityItemEntity fundsItem = securityMap.get(SecurityConst.ITEM_TYPE_FUNDS);//公积金
                SecurityItemDto funds = handleSecurityItem(fundsItem, SecurityConst.ITEM_TYPE_FUNDS, employeeSecurityEntity.getReservedFunds());
                //公积金
                fundsRecordEntity.setReservedFundsOrg(funds.getOrgCost());
                fundsRecordEntity.setReservedFundsOrgRate(funds.getOrgRate());
                fundsRecordEntity.setReservedFundsPerson(funds.getPersonCost());
                fundsRecordEntity.setReservedFundsPersonRate(funds.getPersonRate());
                personTotal.add(funds.getPersonCost());
                orgTotal.add(funds.getOrgCost());
            } else {
                SecurityItemEntity offerFundsItem = securityMap.get(SecurityConst.ITEM_TYPE_OFFER_FUNDS);//补充公积金
                SecurityItemDto offerFunds = handleSecurityItem(offerFundsItem, SecurityConst.ITEM_TYPE_ENDOWMENT, employeeSecurityEntity.getOfferFunds());
                //补充公积金
                fundsRecordEntity.setOfferFundsOrg(offerFunds.getOrgCost());
                fundsRecordEntity.setOfferFundsOrgRate(offerFunds.getOrgRate());
                fundsRecordEntity.setOfferFundsPerson(offerFunds.getPersonCost());
                fundsRecordEntity.setOfferFundsPersonRate(offerFunds.getPersonRate());
                personTotal.add(offerFunds.getPersonCost());
                orgTotal.add(offerFunds.getOrgCost());
            }
        }
        fundsRecordEntity.setPersonCostTotal(personTotal);
        fundsRecordEntity.setOrgCostTotal(orgTotal);
        return R.ok(fundsRecordEntity);
    }


    /**
     * 社保方案修改时更新社保台账
     *
     * @param securityVo
     * @param request
     * @throws Exception
     */
    public void updateSecurityRecord(SecurityVo securityVo, HttpServletRequest request, String name, String code) throws Exception {
        List<EmployeeSecurityDto> employeeSecurityEntityList = new ArrayList<>();
        if (SecurityConst.ITEM_TYPE_ENDOWMENT.equals(securityVo.getType())) {
            employeeSecurityEntityList = employeeSecurityService.getUserSecurityList(securityVo.getSecurityId(), null);
        } else {
            employeeSecurityEntityList = employeeSecurityService.getUserSecurityList(null, securityVo.getSecurityId());
        }
        SecurityChangeVo change = new SecurityChangeVo();
        change.setType(SecurityConst.CHANGE_TYPE_UPDATE);
        change.setOperateTime(new Date());
        change.setSecurityId(securityVo.getSecurityId());
        Map<Integer, SecurityItemEntity> itemMap = new HashMap<>();
        for (SecurityItemEntity itemEntity : securityVo.getSecurityItem()) {
            itemMap.put(itemEntity.getSecurityType(), itemEntity);
        }

        for (EmployeeSecurityDto entity : employeeSecurityEntityList) {
            updateEmployeeSecurity(entity, securityVo, itemMap);
            change.setOid(entity.getOid());
            EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(entity.getOid());
            if (!ObjectUtils.isEmpty(employeeInfoEntity)) {
                change.setOrgId(employeeInfoEntity.getOrgId());
                change.setUnitId(employeeInfoEntity.getUnitId());
            }
            changeSecurity(change, request, name, code);
        }
    }

    /**
     * 更新用户社保/公积金基数信息
     *
     * @param entity
     * @param securityVo
     * @param itemMap
     */
    private void updateEmployeeSecurity(EmployeeSecurityDto entity, SecurityVo securityVo, Map<Integer, SecurityItemEntity> itemMap) {
        EmployeeSecurityEntity securityEntity = BeanUtilsMabach.doToDto(entity, EmployeeSecurityEntity.class);
        if (SecurityConst.SECURITY_TYPE_SECURITY.equals(securityVo.getType())) {
            securityEntity.setDisabledEmployment(getInsurance(itemMap.get(ITEM_TYPE_DISABLED).getLowerLimit(),
                    itemMap.get(ITEM_TYPE_DISABLED).getUpperLimit(), securityEntity.getDisabledEmployment()));
            securityEntity.setEndowmentInsurance(getInsurance(itemMap.get(ITEM_TYPE_ENDOWMENT).getLowerLimit(),
                    itemMap.get(ITEM_TYPE_ENDOWMENT).getUpperLimit(), securityEntity.getEndowmentInsurance()));
            securityEntity.setInjuryInsurance(getInsurance(itemMap.get(ITEM_TYPE_INJURY).getLowerLimit(),
                    itemMap.get(ITEM_TYPE_INJURY).getUpperLimit(), securityEntity.getInjuryInsurance()));
            securityEntity.setLargerMedical(getInsurance(itemMap.get(ITEM_TYPE_LARGER_MEDICAL).getLowerLimit(),
                    itemMap.get(ITEM_TYPE_LARGER_MEDICAL).getUpperLimit(), securityEntity.getLargerMedical()));
            securityEntity.setMaternityInsurance(getInsurance(itemMap.get(ITEM_TYPE_MATERNITY).getLowerLimit(),
                    itemMap.get(ITEM_TYPE_MATERNITY).getUpperLimit(), securityEntity.getMaternityInsurance()));
            securityEntity.setMedicalInsurance(getInsurance(itemMap.get(ITEM_TYPE_MEDICAL).getLowerLimit(),
                    itemMap.get(ITEM_TYPE_MEDICAL).getUpperLimit(), securityEntity.getMedicalInsurance()));
            securityEntity.setUnemploymentInsurance(getInsurance(itemMap.get(ITEM_TYPE_UNEMPLOYMENT).getLowerLimit(),
                    itemMap.get(ITEM_TYPE_UNEMPLOYMENT).getUpperLimit(), securityEntity.getUnemploymentInsurance()));
        } else {
            securityEntity.setReservedFunds(getInsurance(itemMap.get(ITEM_TYPE_FUNDS).getLowerLimit(),
                    itemMap.get(ITEM_TYPE_FUNDS).getUpperLimit(), securityEntity.getReservedFunds()));
            securityEntity.setOfferFunds(getInsurance(itemMap.get(ITEM_TYPE_OFFER_FUNDS).getLowerLimit(),
                    itemMap.get(ITEM_TYPE_OFFER_FUNDS).getUpperLimit(), securityEntity.getOfferFunds()));
        }
        employeeSecurityService.updateByIdE(securityEntity);
    }

    /**
     * 比对方案子项上下限与当前基数适用范围
     *
     * @param lower
     * @param upper
     * @param now
     * @return
     */
    private BigDecimal getInsurance(BigDecimal lower, BigDecimal upper, BigDecimal now) {
        if (ObjectUtils.isEmpty(now) || lower.compareTo(now) > 0) {
            return lower;
        } else if (upper.compareTo(now) < 0) {
            return upper;
        }
        return now;
    }

    /**
     * bigDecimal计算
     *
     * @param a
     * @param b
     * @return
     */
    private BigDecimal getTotal(BigDecimal a, BigDecimal b) {
        a = !ObjectUtils.isEmpty(a) ? a : new BigDecimal(0);
        b = !ObjectUtils.isEmpty(b) ? b : new BigDecimal(0);
        return a.add(b);
    }

    private R isConfirm(SecurityRecordUpdateVo vo) {
        Map<Long, Integer> securityMap = new HashMap<>();
        Map<Long, Object> map = new HashMap<>();
        String startTime = DateUtils.format(new Date(), "yyyy-MM") + "-01 00:00:00";
        String endTime = DateUtils.format(new Date(), "yyyy-MM") + "-31 23:59:59";
        //判断当月是否有汇缴已确认过的
        if (!RECORD_TYPE_CHECK.equals(vo.getStatus())) {
            for (String id : vo.getRecordId()) {
                String orgName = null;
                EmployeeSecurityEntity entity = null;
                Long securityId = null;
                if (SECURITY_TYPE_FUNDS.equals(vo.getType())) {
                    FundsRecordEntity recordEntity = fundsRecordService.getByIdE(Long.parseLong(id));
                    entity = employeeSecurityDao.selectOne(new QueryWrapper<EmployeeSecurityEntity>().eq("oid", recordEntity.getOid()).eq("is_delete", 0));
                    orgName = recordEntity.getUnitName();
                    securityId = entity.getFundsId();
                    map.put(Long.parseLong(id), recordEntity);
                } else {
                    SecurityRecordEntity recordEntity = securityRecordService.getByIdE(Long.parseLong(id));
                    entity = employeeSecurityDao.selectOne(new QueryWrapper<EmployeeSecurityEntity>().eq("oid", recordEntity.getOid()).eq("is_delete", 0));
                    orgName = recordEntity.getUnitName();
                    securityId = entity.getSecurityId();
                    map.put(Long.parseLong(id), recordEntity);
                }
                if (ObjectUtils.isEmpty(securityMap.get(securityId))) {
                    int count = 0;
                    if (SECURITY_TYPE_FUNDS.equals(vo.getType())) {
                        count = fundsRecordService.getConfirmRecordCount(securityId.toString(), startTime, endTime, vo.getType());
                    } else {
                        count = securityRecordService.getConfirmRecordCount(securityId.toString(), startTime, endTime, vo.getType());
                    }

                    if (count > 0) {
                        return R.error(orgName + "本月汇缴已确认，不能再增员");
                    }
                    securityMap.put(securityId, count);
                } else if (securityMap.get(securityId) > 0) {
                    return R.error(orgName + "本月汇缴已确认，不能再增员");
                }
            }
        }
        return R.ok(map);
    }

    @PostMapping("/addDisabledOrLargerInfo")
    @ApiOperation("缴纳残疾人保障金/重大医疗")
    @PreAuthorize("hasAuthority('emp:socialSecurity:update')")
    @Transactional
    public R addDisabledOrLargerInfo(@RequestBody @Valid DisabledMaternityVo vo, HttpServletRequest request) throws Exception {
        Date date = new Date();
        for (String oid : vo.getOids()) {
            SecurityChangeVo changeEntity = new SecurityChangeVo();
            changeEntity.setOid(Long.parseLong(oid));
            changeEntity.setSecurityId(Long.parseLong(vo.getSecurityId()));
            changeEntity.setOperateTime(date);
            changeEntity.setType(CHANGE_TYPE_UPDATE);
            EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(Long.parseLong(oid));
            if (!ObjectUtils.isEmpty(employeeInfoEntity)) {
                changeEntity.setOrgId(employeeInfoEntity.getOrgId());
                changeEntity.setUnitId(employeeInfoEntity.getUnitId());
            }
            R changeR = changeSecurity(changeEntity, request, null, null);
            if (changeR.getFlag()) {
                String startDay = DateUtils.format(date, "yyyy-MM") + "-01 00:00:00";
                String endDay = DateUtils.format(date, "yyyy-MM") + "-31 23:59:59";
                SecurityRecordEntity oldRecord = securityRecordService.getByOidAndType(Long.parseLong(oid), 0, startDay, endDay);
                if (ITEM_TYPE_LARGER_MEDICAL.equals(vo.getType())) {
                    oldRecord.setLargerMedicalPerson(vo.getAmountPerson());
                    oldRecord.setLargerMedicalOrg(vo.getAmountOrg());
                } else {
                    oldRecord.setDisabledEmploymentOrg(vo.getAmountOrg());
                    oldRecord.setDisabledEmploymentPerson(vo.getAmountPerson());
                }
                oldRecord.setPersonCostTotal(getTotal(vo.getAmountPerson(), oldRecord.getPersonCostTotal()));
                oldRecord.setSalaryCost(getTotal(vo.getAmountPerson(), oldRecord.getPersonCostTotal()));
                oldRecord.setOrgCostTotal(getTotal(vo.getAmountOrg(), oldRecord.getOrgCostTotal()));
                securityRecordService.updateByIdE(oldRecord);
            }

        }
        return R.ok();
    }

    @PostMapping("/deleteSecurityRecord")
    @ApiOperation("删除社保台账记录")
    @PreAuthorize("hasAuthority('emp:socialSecurity:update')")
    @Transactional
    public R deleteSecurityRecord(String recordId) {
        securityRecordService.removeOneById(Long.parseLong(recordId));
        return R.ok();
    }


    @DeleteMapping("/deleteSecurityRecordAll")
    @ApiOperation("删除全部社保台账记录")
    public R deleteSecurityRecordAll(String unitId) {
        // 查询社保台账
        List<SecurityRecordDto> entities = securityRecordDao.getRecordDelete(0, 0, Long.parseLong(unitId));

        if (!CollectionUtils.isEmpty(entities)) {
            for (SecurityRecordDto se : entities
            ) {
                securityRecordDao.deleteAllSecurity(se.getUnitId());

            }
        }
        return R.ok();
    }

    @DeleteMapping("/deleteSecurityRecordByIds")
    @ApiOperation("批量删除根据社保台账记录")
    @Transactional
    public R deleteSecurityRecordAll(String[] recordIds) {
        for (String recordId : recordIds
        ) {
            securityRecordService.removeOneById(Long.parseLong(recordId));

        }
        return R.ok();
    }

    @DeleteMapping("/deleteFundsRecordByIds")
    @ApiOperation("批量删除根据公积金台账记录")
    @Transactional
    public R deleteFundsRecordAll(String[] recordIds) {
        for (String recordId : recordIds
        ) {
            fundsRecordService.removeOneById(Long.parseLong(recordId));

        }
        return R.ok();
    }

    @DeleteMapping("/deleteFundsRecordAll")
    @ApiOperation("删除全部公积金台账记录")
    public R deleteFundsRecordAll(@RequestParam("unitId") String unitId) {
        //查询公积金台账
        List<FundsRecordDto> entities = fundsRecordDao
                .getFundDeleteAll(0, Long.parseLong(unitId));
        if (!CollectionUtils.isEmpty(entities)) {
            for (FundsRecordDto frd : entities
            ) {
                fundsRecordDao.deleteAllFund(frd.getUnitId());

            }
        }
        return R.ok();
    }


    @PostMapping("/deleteFundsRecord")
    @ApiOperation("删除社保台账记录")
    @PreAuthorize("hasAuthority('emp:socialSecurity:update')")
    @Transactional
    public R deleteFundsRecord(@RequestParam("recordId") String recordId) {
        fundsRecordService.removeOneById(Long.parseLong(recordId));
        return R.ok();
    }

    @PostMapping("/getMemberChange")
    @ApiOperation("查询社保公积金人员变更记录")
    @PreAuthorize("hasAuthority('emp:socialSecurity:get')")
    public R<List<SecurityMemberChangeListDto>> getMemberChange(@RequestBody @Valid SecurityMemberChangeVo vo, HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        String beginDate = DateUtils.format(vo.getDate(), "yyyy-MM") + "-01 00:00:00";
        String endDate = DateUtils.format(vo.getDate(), "yyyy-MM") + "-31 23:59:59";
        List<SecurityMemberChangeListDto> list = securityChangeDao.getMemberChangeList(vo.getSecurityId(), beginDate, endDate);
        for (SecurityMemberChangeListDto changeListDto : list) {
            changeListDto.setNationName(jobController.nationality.get(changeListDto.getNationality()));
        }
        return R.ok(list);
    }

    // 改为社保权限
    @PostMapping("/getSecurityBatch")
    @ApiOperation("获取社保公积金批次列表")
    @PreAuthorize("hasAuthority('emp:socialSecurity:get')")
    public R<PageResult<SecurityBatchEntity>> getSecurityBatch(@RequestBody @Valid SecurityBatchVo vo, HttpServletRequest request) throws Exception {
        String time = "";
        String endTime = "";

        //检查是否有主体组权限
        R checkC = loginController.checkContractPermission(request);
        if (!R.isOk.equals(checkC.getStatus())) {
            return checkC;
        }
        List<ContractSubGroupEntity> contractSubs = (List<ContractSubGroupEntity>) checkC.getData();
        ArrayList<Long> contractIds = new ArrayList<Long>();
        for (ContractSubGroupEntity item : contractSubs
        ) {
            contractIds.add(item.getId());
        }

        if (!ObjectUtils.isEmpty(vo.getTime())) {
            time = DateUtils.format(vo.getTime(), "yyyy-MM") + "-01 00:00:00";
            endTime = DateUtils.format(vo.getTime(), "yyyy-MM") + "-31 23:59:59";
        }
        PageResult<SecurityBatchEntity> pageResult = securityBatchService.queryPageAuth(contractIds, vo.getUnitName(), vo.getOrgName(), vo.getName(), time, endTime,
                vo.getType(), vo.getPageNum(), vo.getPageSize());
        return R.ok(pageResult);
    }

    @PostMapping("/getSecurityBatchGroupList")
    @ApiOperation("获取社保批次详情列表")
    @PreAuthorize("hasAuthority('emp:socialSecurity:get')")
    public R<List<SecurityRecordDto>> getSecurityBatchGroupList(String id, HttpServletRequest request) throws Exception {
//        //获取当前用户角色下公司Id 主体组权限
//        R checkR = loginController.checkOrgPermission(request,null,false);
//        if(!R.isOk.equals(checkR.getStatus())){
//            return checkR;
//        } leeirm
//        List<Long> orgIds = (List<Long>) checkR.getData();
        R checkC = loginController.checkContractPermission(request);
        if (!R.isOk.equals(checkC.getStatus())) {
            return checkC;
        }
        List<ContractSubGroupEntity> contractSubs = (List<ContractSubGroupEntity>) checkC.getData();
        ArrayList<Long> contractIds = new ArrayList<Long>();
        for (ContractSubGroupEntity item : contractSubs
        ) {
            contractIds.add(item.getId());
        }
        List<SecurityRecordDto> result = securityBatchGroupDao.getSecurityBatchGroupList(id, contractIds);
        return R.ok(result);
    }

    @PostMapping("/getFundsBatchGroupList")
    @ApiOperation("获取公积金批次详情列表")
    @PreAuthorize("hasAuthority('emp:socialSecurity:get')")
    public R<List<FundsRecordDto>> getFundsBatchGroupList(String id, HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id 主体组权限
//        R checkR = loginController.checkOrgPermission(request,null,false);
//        if(!R.isOk.equals(checkR.getStatus())){
//            return checkR;
//        }
//        List<Long> orgIds = (List<Long>) checkR.getData();
        R checkC = loginController.checkContractPermission(request);
        if (!R.isOk.equals(checkC.getStatus())) {
            return checkC;
        }
        List<ContractSubGroupEntity> contractSubs = (List<ContractSubGroupEntity>) checkC.getData();
        ArrayList<Long> contractIds = new ArrayList<Long>();
        for (ContractSubGroupEntity item : contractSubs
        ) {
            contractIds.add(item.getId());
        }

        List<FundsRecordDto> result = securityBatchGroupDao.getFundsBatchGroupList(id, contractIds);
        return R.ok(result);
    }


    //主体组权限
    @PostMapping("/getSecurityRecordReportList")
    @ApiOperation("查询-社保报表")
    public R<PageResult<SecurityRecordReportDto>> getSecurityRecordReportList(@RequestBody @Valid SecurityRecordReportVo securityRecordVo
            , HttpServletRequest request) throws Exception {
        String time = "";
        String endTime = "";
        //获取当前用户角色下公司Id
//        R checkR = loginController.checkOrgPermission(request,null,false);
//        if(!R.isOk.equals(checkR.getStatus())){
//            return checkR;
//        }
//        List<Long> orgIds = (List<Long>) checkR.getData();


        R checkC = loginController.checkContractPermission(request);
        if (!R.isOk.equals(checkC.getStatus())) {
            return checkC;
        }
        List<ContractSubGroupEntity> contractSubs = (List<ContractSubGroupEntity>) checkC.getData();
        ArrayList<Long> contractIds = new ArrayList<Long>();
        for (ContractSubGroupEntity item : contractSubs
        ) {
            contractIds.add(item.getId());
        }

        //判断是按年还是按月结算
        if (!ObjectUtils.isEmpty(securityRecordVo.getOperateTime()) && securityRecordVo.getIsAllYear().equals(1)) {
            time = DateUtils.format(securityRecordVo.getOperateTime(), "yyyy-MM") + "-01 00:00:00";
            endTime = DateUtils.format(securityRecordVo.getOperateTime(), "yyyy-MM") + "-31 23:59:59";
        } else if (!ObjectUtils.isEmpty(securityRecordVo.getOperateTime()) && securityRecordVo.getIsAllYear().equals(0)) {
            time = DateUtils.format(securityRecordVo.getOperateTime(), "yyyy") + "-01 00:00:00";
            endTime = DateUtils.format(securityRecordVo.getOperateTime(), "yyyy") + "-12-31 23:59:59";
        }
        PageResult<SecurityRecordReportDto> recordMap = securityRecordService.getRecordReportList(contractIds, time, endTime,
                1,//已确认
                securityRecordVo.getName(),
                securityRecordVo.getUnitName(),
                securityRecordVo.getPageNum(), securityRecordVo.getPageSize());

        return R.ok(recordMap);
    }


    @PostMapping("/getFundsRecordReportList")
    @ApiOperation("查询公积金报表")
    public R<PageResult<FundsRecordReportDto>> getFundsRecordReportList(@RequestBody @Valid SecurityRecordReportVo securityRecordVo, HttpServletRequest request) throws Exception {
        String time = "";
        String endTime = "";
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();

        R checkC = loginController.checkContractPermission(request);
        if (!R.isOk.equals(checkC.getStatus())) {
            return checkC;
        }
        List<ContractSubGroupEntity> contractSubs = (List<ContractSubGroupEntity>) checkC.getData();
        ArrayList<Long> contractIds = new ArrayList<Long>();
        for (ContractSubGroupEntity item : contractSubs
        ) {
            contractIds.add(item.getId());
        }


        //判断是按年还是按月结算
        if (!ObjectUtils.isEmpty(securityRecordVo.getOperateTime()) && securityRecordVo.getIsAllYear().equals(1)) {
            time = DateUtils.format(securityRecordVo.getOperateTime(), "yyyy-MM") + "-01 00:00:00";
            endTime = DateUtils.format(securityRecordVo.getOperateTime(), "yyyy-MM") + "-31 23:59:59";
        } else if (!ObjectUtils.isEmpty(securityRecordVo.getOperateTime()) && securityRecordVo.getIsAllYear().equals(0)) {
            time = DateUtils.format(securityRecordVo.getOperateTime(), "yyyy") + "-01 00:00:00";
            endTime = DateUtils.format(securityRecordVo.getOperateTime(), "yyyy") + "-12-31 23:59:59";
        }
        PageResult<FundsRecordReportDto> recordMap = fundsRecordService.getRecordReportList(contractIds, time, endTime, 1
                , securityRecordVo.getUnitName(), securityRecordVo.getName(),
                securityRecordVo.getPageNum(), securityRecordVo.getPageSize());

        return R.ok(recordMap);
    }


    @PostMapping("/refreshSecurityRecord")
    @ApiOperation("刷新社保&公积金台账")
    @Transactional
    public R refreshSecurityRecord(@RequestParam Long unitId,@RequestParam(value = "type", defaultValue = "0") Integer type,HttpServletRequest request) throws Exception {
        R uR = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) uR.getData();
        String userCode;
        String name;
        if (!ObjectUtils.isEmpty(user)) {
            userCode = user.getString("usercode");
            name = user.getString("name");
        }else {
            return  R.error( "请先登录!");
        }
        String startMonth = DateUtils.getBeginDayOfMonth();
        String endMonth = DateUtils.getLastDayOfMonth();
        Date operateTime = DateUtils.parseDateYMD(startMonth);
        if (type.equals(0)){
            List<SecurityRecordDto> securityRecordConfirm = securityRecordDao.getSecurityRecord(
                    startMonth+" 00:00:00",endMonth+" 23:59:59",null,1,unitId);
            if(securityRecordConfirm.size()>0){
              return  R.error( "当月已有确认过的缴费记录，无法刷新台账!");
            }
            List<SecurityRecordDto> securityRecordNotConfirm = securityRecordDao.getSecurityRecord(
                    startMonth+" 00:00:00",endMonth+" 23:59:59",null,0,unitId);
            List<Long> ids=new ArrayList<>();
            for (SecurityRecordDto securityRecordDto:securityRecordNotConfirm){
                ids.add(securityRecordDto.getRecordId());
            }
            securityRecordService.removeByIdsE(ids);

            List<EmployeeSecurityEntity> userSecurityEntities = employeeSecurityDao.selectList(new QueryWrapper<EmployeeSecurityEntity>().eq("is_delete", 0));
            for (EmployeeSecurityEntity employeeSecurityEntity : userSecurityEntities) {
                //添加社保缴费记录
                if (!ObjectUtils.isEmpty(employeeSecurityEntity.getSecurityId())) {
                    SecurityEntity securityEntity = jobController.sMap.get(employeeSecurityEntity.getSecurityId());
                    if(!ObjectUtils.isEmpty(securityEntity)&&unitId.equals(securityEntity.getContractMainId())&&securityEntity.getType().equals(0)){
                        SecurityRecordEntity securityRecordEntity = new SecurityRecordEntity();
                        securityRecordEntity.setCreateTime(new Date());
                        securityRecordEntity.setOperateTime(operateTime);
                        securityRecordEntity.setOid(employeeSecurityEntity.getOid());
                        securityRecordEntity.setUnitName(securityEntity.getUnitName());
                        securityRecordEntity.setCityName(securityEntity.getCityName());
                        securityRecordEntity.setSecurityId(securityEntity.getSecurityId());
                        addSecurityRecord(employeeSecurityEntity.getOid(), userCode, name, securityRecordEntity, operateTime, CHANGE_TYPE_NORMAL);
                    }

               }
            }
        }else{
            List<FundsRecordDto>  fundsRecordConfirm = fundsRecordDao.getFundsRecord(
                    startMonth+" 00:00:00",endMonth+" 23:59:59",1,unitId);
            if(fundsRecordConfirm.size()>0){
                return  R.error( "当月已有确认过的缴费记录，无法刷新台账!");
            }
            List<FundsRecordDto> fundsRecordNotConfirm = fundsRecordDao.getFundsRecord(
                    startMonth+" 00:00:00",endMonth+" 23:59:59",0,unitId);
            List<Long> ids=new ArrayList<>();
            for (FundsRecordDto fundsRecordDto:fundsRecordNotConfirm){
                ids.add(fundsRecordDto.getRecordId());
            }
            fundsRecordService.removeByIdsE(ids);

            List<EmployeeSecurityEntity> userSecurityEntities = employeeSecurityDao.selectList(new QueryWrapper<EmployeeSecurityEntity>().eq("is_delete", 0));
            for (EmployeeSecurityEntity employeeSecurityEntity : userSecurityEntities) {
                //添加社保缴费记录
                if (!ObjectUtils.isEmpty(employeeSecurityEntity.getFundsId())) {
                    SecurityEntity securityEntity = jobController.sMap.get(employeeSecurityEntity.getFundsId());
                    if(!ObjectUtils.isEmpty(securityEntity)&&unitId.equals(securityEntity.getContractMainId())&&securityEntity.getType().equals(1)){
                        FundsRecordEntity fundsRecordEntity = new FundsRecordEntity();
                        fundsRecordEntity.setCreateTime(new Date());
                        fundsRecordEntity.setOperateTime(operateTime);
                        fundsRecordEntity.setOid(employeeSecurityEntity.getOid());
                        fundsRecordEntity.setUnitName(securityEntity.getUnitName());
                        fundsRecordEntity.setCityName(securityEntity.getCityName());
                        fundsRecordEntity.setSecurityId(securityEntity.getSecurityId());
                        addFundsRecord(employeeSecurityEntity.getOid(), userCode, name, fundsRecordEntity, operateTime, CHANGE_TYPE_NORMAL);
                    }
                }
            }
        }
        return R.ok();
    }


}
